这是一段玩具代码,说明了我的问题:
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轴数据以进行更新?
首先关于blitting:Blitting仅适用于轴的内容。它会影响轴的内部,但不影响外轴装饰器。因此,如果使用blit=True
,轴装饰器不会更新。或者反过来说,如果你想要更新比例,你需要使用blit=False
。
现在,在问题的情况下,这会导致不绘制线。原因是该行的animated
属性设置为True
。但是,默认情况下不会绘制“动画”艺术家。这个属性实际上是用于blitting;但是如果没有进行blitting,那么艺术家既不会画画也不会画布。调用这个属性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()