简体   繁体   English

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

[英]Matplotlib Animation: how to dynamically extend x limits?

I have a simple animation plot like so:我有一个简单的动画情节,如下所示:

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()

Now, this works okay, but I want it to expand like one of the subplots in here http://www.roboticslab.ca/matplotlib-animation/ where the x-axis dynamically extends to accommodate the incoming data points.现在,这可以正常工作,但我希望它像http://www.roboticslab.ca/matplotlib-animation/中的子图之一一样扩展,其中 x 轴动态扩展以容纳传入的数据点。

How do I accomplish this?我该如何实现?

I came across this problem (but for set_ylim) and I had some trial and error with the comment of @ImportanceOfBeingErnest and this is what I got, adapted to @nz_21 question.我遇到了这个问题(但对于 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)

Actually in the web quoted by @nz_21 there is a similar solution.实际上在@nz_21 引用的网络中,有一个类似的解决方案。

There is a workaround for this even when blit=True if you send a resize event to the canvas, forcing MPL to flush the canvas.如果您向画布发送调整大小事件,强制 MPL 刷新画布,即使blit=True也有解决方法。 To be clear, the fact that the code in @fffff answer doesn't work with blit is a bug in the MPL codebase, but if you add fig.canvas.resize_event() after setting the new x-axis, it will work in MPL 3.1.3.需要明确的是,@ffffff 答案中的代码不适用于 blit 是 MPL 代码库中的一个错误,但是如果您在设置新的 x 轴后添加fig.canvas.resize_event() ,它将在MPL 3.1.3。 Of course, you should only do this sporadically to actually get any benefit from blitting --- if you're doing it every frame, you're just performing the non-blit procedure anyway, but with extra steps.当然,您应该只是偶尔这样做才能真正从 blitting 中获得任何好处——如果您每帧都这样做,那么无论如何您只是在执行非 blit 过程,但需要额外的步骤。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM