Matplotlib 动画不更新刻度标签

6 投票
1 回答
5478 浏览
提问于 2025-04-17 13:16

我正在尝试修改一个示例,让动画在x值增加时运行。我想让x轴的刻度标签根据x值进行更新。

我想使用1.2版本中的动画功能(特别是FuncAnimation)。我可以设置x轴的范围,但刻度标签没有更新。我也尝试过明确设置刻度标签,但这也没有效果。

我看到这个链接:Animating matplotlib axes/ticks,我尝试调整animation.py中的bbox,但没有成功。我对matplotlib还比较陌生,不太清楚具体发生了什么,所以希望能得到一些帮助。

谢谢

"""
Matplotlib Animation Example

author: Jake Vanderplas
email: vanderplas@astro.washington.edu
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""

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(ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# 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 = np.linspace(i, i+2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    ax.set_xlim(i, i+2)

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

1 个回答

9

可以查看以下链接了解更多内容:动画化matplotlib的坐标轴/刻度python matplotlib如何在坐标轴或图形的边缘进行blit?,还有matplotlib中的动画标题

简单来说,就是去掉 blit=True

anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20)

当你设置 blit=True 时,只有那些发生变化的部分会被重新绘制,而不是全部重新绘制,这样可以提高渲染效率。只有在更新函数(这里是 animate)返回的部分才会被标记为发生了变化。还有一点需要注意的是,代码在 animation.py 中的工作方式要求这些部分必须在坐标轴的边界框内。想了解更多,可以查看上面提到的链接。

撰写回答