这是一段演示我的问题的代码:
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-asis 数据?
最佳答案
首先是关于 block 传输: block 传输仅应用于轴的内容。它会影响轴的内部,但不会影响外部轴装饰器。因此,如果使用 blit=True
,则轴装饰器不会更新。或者反过来说,如果你想让刻度更新,你需要使用blit=False
。
现在,在问题的情况下,这导致未绘制线。原因是该行的 animated
属性设置为 True
。但是,默认情况下不会绘制“动画”艺术家。这个属性实际上是用来进行 blitting 的;但如果不执行 blitting,则会导致 artist 既不被绘制也不被 blit。将此属性称为 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()
关于python - 更新 matplotlib 动画中的 x 轴标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52219056/