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

6

我有一个简单的动画图,如下所示:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = 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 frame
def init():
    line.set_data([], [])
    return line,


# animation function.  This is called sequentially
def 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轴动态扩展以容纳传入的数据点。

我该如何实现这个功能?


3
使用blitting时无法这样做。但是,如果关闭它,您可以在动画函数中使用ax.set_xlim(newxmin,newxmax)来更改限制。 - ImportanceOfBeingErnest
@ImportanceOfBeingErnest 太棒了,谢谢,它起作用了! :) - nz_21
2个回答

3

我遇到了这个问题(但是对于set_ylim),我根据@ImportanceOfBeingErnest的评论进行了一些尝试和错误,并适应了@nz_21的问题。

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)

实际上,在由@nz_21引用的网页中,有一个类似的解决方案。您可以参考一下。


2
即使在blit=True的情况下,这个问题也有一个解决方法,即向画布发送一个调整大小的事件,强制MPL刷新画布。需要明确的是,在@fffff回答中的代码无法与blit一起使用是MPL代码库中的一个错误,但如果在设置新的x轴后添加fig.canvas.resize_event(),它将在MPL 3.1.3中运行。当然,你应该偶尔这样做才能从blitting中获得任何好处---如果你每帧都这样做,那么你只是执行非blit过程,但增加了额外的步骤。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接