两个问题。直接的问题是标题不属于要更新的艺术家列表的一部分,因此动画无法知道您想要更新它。
更深刻的问题是每个轴只有一个标题。因此,即使您将标题包含在艺术家列表中,它也将始终显示上次设置的文本。
解决方案是不使用轴的标题进行更新,而是使用其他文本元素(每帧一个)进行更新。
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
a = np.random.rand(10,10)
fig, ax=plt.subplots()
container = []
for i in range(a.shape[1]):
line, = ax.plot(a[:,i])
title = ax.text(0.5,1.05,"Title {}".format(i),
size=plt.rcParams["axes.titlesize"],
ha="center", transform=ax.transAxes, )
container.append([line, title])
ani = animation.ArtistAnimation(fig, container, interval=200, blit=False)
plt.show()
供参考,与FuncAnimation
如下所示,可以像往常一样直接设置标题。
import matplotlib.pyplot as plt
from matplotlib import animation
import numpy as np
a = np.random.rand(10,10)
fig, ax=plt.subplots()
ax.axis([-0.5,9.5,0,1])
line, = ax.plot([],[])
def animate(i):
line.set_data(np.arange(len(a[:,i])),a[:,i])
ax.set_title("Title {}".format(i))
ani = animation.FuncAnimation(fig,animate, frames=a.shape[1], interval=200, blit=False)
plt.show()