【问题标题】:Updating x-axis labels in matplotlib animation在 matplotlib 动画中更新 x 轴标签
【发布时间】:2018-09-07 09:02:26
【问题描述】:

这是一个说明我的问题的玩具代码:

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 轴数据”?

【问题讨论】:

  • 使用animated=Falseblit=False。我可能会写一个完整的答案,并解释为什么稍后会这样做。
  • @ImportanceOfBeingErnest WOT?!好的,我非常感谢您在这里进行深入的解释。我很困惑。顺便说一句,爱你的名字!好戏……☺

标签: python animation matplotlib


【解决方案1】:

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

现在,在问题的情况下,这导致没有画线。原因是该行的animated 属性设置为True。但是,默认情况下不绘制“动画”艺术家。这个属性实际上是用于 blitting;但如果不执行 blitting 将导致艺术家既不被绘制也不被 blitted。将此属性称为 blit_include 或类似名称可能是个好主意,以避免与其名称混淆。
不幸的是,它看起来也没有很好的记录。但是,您会在 source code 中找到一条评论

# 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 因为我忘了这样做。谢谢你提醒我。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 2017-03-25
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 2017-08-24
相关资源
最近更新 更多