Matplotlib动画不更新刻度标签。

6
我正在尝试通过增加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()

你的问题有更好的答案,请查看编辑。 - tacaswell
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中正常工作。请参考顶部链接中的其中一个来处理这个问题。


2
谢谢您的回答。不过这会重新绘制所有内容。我希望网格线和刻度是固定的。我想要能够更改x轴标签上的文本。 - Jared
@Jared,您是指刻度上的标签还是轴上的标签? - tacaswell

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