为了账号安全,请及时绑定邮箱和手机立即绑定

Matplotlib 动画:如何动态扩展 x 限制?

Matplotlib 动画:如何动态扩展 x 限制?

鸿蒙传说 2021-08-24 19:05:26
我有一个简单的动画情节,如下所示:import numpy as npfrom matplotlib import pyplot as pltfrom matplotlib import animation# First set up the figure, the axis, and the plot element we want to animatefig = plt.figure()ax = plt.axes(xlim=(0, 100), ylim=(0, 100))line, = ax.plot([], [], lw=2)x = []y = []# initialization function: plot the background of each framedef init():    line.set_data([], [])    return line,# animation function.  This is called sequentiallydef animate(i):    x.append(i + 1)    y.append(10)    line.set_data(x, y)    return line,# call the animator.  blit=True means only re-draw the parts that have changed.anim = animation.FuncAnimation(fig, animate, init_func=init,                               frames=200, interval=20, blit=True)plt.show()现在,这可以正常工作,但我希望它像http://www.roboticslab.ca/matplotlib-animation/中的子图之一一样扩展,其中 x 轴动态扩展以容纳传入的数据点。我该如何实现?
查看完整描述

2 回答

?
慕田峪4524236

TA贡献1875条经验 获得超5个赞

我遇到了这个问题(但对于 set_ylim)并且我对@ImportanceOfBeingErnest 的评论进行了一些试验和错误,这就是我得到的。


def animate(i):

    x.append(i + 1)

    y.append(10)

    ax.set_xlim(min(x), max(x)) #added ax attribute here

    line.set_data(x, y)


    return line, 


# call the animator.  blit=True means only re-draw the parts that have changed.

anim = animation.FuncAnimation(fig, animate, init_func=init,

                               frames=500, interval=20)

查看完整回答
反对 回复 2021-08-24
?
浮云间

TA贡献1829条经验 获得超4个赞

即使blit=True您向画布发送调整大小事件,强制 MPL 刷新画布,也有一种解决方法。需要明确的是,@fffff 答案中的代码不适用于 blit 的事实是 MPL 代码库中的一个错误,但如果您fig.canvas.resize_event()在设置新的 x 轴后添加,它将在 MPL 3.1.3 中工作。当然,您应该只是偶尔这样做才能真正从 blitting 中获得任何好处——如果您每帧都这样做,那么无论如何您只是在执行非 blit 过程,但需要额外的步骤。


查看完整回答
反对 回复 2021-08-24
  • 2 回答
  • 0 关注
  • 240 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号