【问题标题】:Matplotlib Animation: how to dynamically extend x limits?Matplotlib 动画:如何动态扩展 x 限制?
【发布时间】:2019-04-24 17:15:35
【问题描述】:

我有一个像这样的简单动画情节:

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 轴动态扩展以容纳传入的数据点。

我该如何做到这一点?

【问题讨论】:

  • 在使用 blitting 时不能这样做。但是如果你关闭它,你可以使用ax.set_xlim(newxmin, newxmax) 来改变你的动画函数的限制。
  • @ImportanceOfBeingErnest 太棒了,谢谢,成功了! :)

标签: python python-3.x animation matplotlib


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我遇到了这个问题(但对于 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 的quoted 网上也有类似的解决方案。

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 2013-06-17
      • 2017-03-25
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多