在Matplotlib动画中更新x轴标签

5

这是一个示例代码,它涉及到我的问题:

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

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], '-o', animated=True)


def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,


def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    ax.set_xlim(np.amin(xdata), np.amax(xdata))
    return ln,


ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

如果我设置blit=True,则数据点会按照我想要的方式绘制。然而,x轴标签/刻度仍保持静态。
如果我设置blit=False,那么x轴标签和刻度会按照我想要的方式更新。然而,没有任何数据点被绘制出来。
如何同时获得绘制的数据(正弦曲线)和x轴数据更新?

2
使用animated=Falseblit=False。稍后我可能会写一篇完整的答案并解释为什么这样做。 - ImportanceOfBeingErnest
@ImportanceOfBeingErnest 什么?!好的,我真的很希望在这里得到一个深入的解释。我感到困惑。顺便说一下,我喜欢你的名字!伟大的戏剧...☺ - Sardathrion - against SE abuse
1个回答

8

首先关于blitting: Blitting仅适用于轴的内容。它将影响轴的内部部分,但不影响外部轴装饰。因此,如果使用blit=True,则轴装饰将不会更新。反过来说,如果您想要更新比例尺,则需要使用blit=False

现在,在问题的情况下,这导致线条没有被绘制。原因是该线条的animated属性设置为True。然而,“animated”艺术家默认情况下不会被绘制。实际上,此属性是用于blitting的;但是,如果不执行blitting,则结果艺术家既不会被绘制也不会被blitted。可能将此属性命名为blit_include或类似名称以避免其名称引起的混淆是个好主意。
不幸的是,看起来它的文档也不太好。但是,您可以在源代码中找到一条注释。

# if the artist is animated it does not take normal part in the
# draw stack and is not expected to be drawn as part of the normal
# draw loop (when not saving) so do not propagate this change
因此,在大多数情况下,可以忽略这个参数的存在,除非您使用blitting。即使使用blitting,也可以在大多数情况下忽略它,因为该属性已在内部设置。
总之,解决方案是不使用"animated"和"blit"。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], '-o')


def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)


def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    ax.set_xlim(np.amin(xdata), np.amax(xdata))


ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init)
plt.show()

@Eric 因为我忘记了。谢谢你提醒我。 - Sardathrion - against SE abuse

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