如何在Matplotlib动画中创建动态标题

3

我正在尝试创建一个Matplotlib动画,每个帧的标题都会改变。到目前为止,这就是我所拥有的(基本上是从matplotlib.org盲目复制/粘贴);A包含我要绘制的数据,textVec包含我想要添加的标题:

fig = plt.figure()

textVec = ['Period ' + str(i[0]) + ' to ' + str(i[1]) + '.'
for i in sliceVec]

ims = []
for i in A:
   ims.append((ax = plt.pcolormesh(i), ))

plt.xlabel(r'$\omega$', size = 22)
plt.ylabel(r'$\gamma$', size = 22)

im_ani = animation.ArtistAnimation(fig, ims, interval=300,
   repeat_delay=1000, blit=True)

以上方法可行,但如何添加这些标题?
祝好。

2
我没有使用过ArtistAnimation,但是记得标题只是Text对象,而Text对象也是artist对象。 - tacaswell
我加入你的问题...你成功解决了吗? - Ohm
2个回答

2

虽然这是一个老问题,但我花了半天的时间尝试使用animation.ArtistAnimation()为每个帧获取单独的标题,但它就是不起作用。
我最接近的尝试是设置注释,但它一旦在图表上方(某种方式在绘制区域之外)就会消失。

对我有用的方法是animation.FuncAnimation()
由于初始问题中没有给出数据,所以我进行了一些设置。

# generate dummy data
data = []
for i in range(10):
    # make these smaller to increase the resolution
    dx, dy = 0.05, 0.05
    # generate 2 2d grids for the x & y bounds
    y, x = np.mgrid[slice(-5, 5 + dy, dy),
                    slice(-5, 5 + dx, dx)]   
    z = np.cos((x*x + y*y) - i*2*np.pi/10)
    # x and y are bounds, so z should be the value *inside* those bounds.
    # Therefore, remove the last value from the z array.
    z = z[:-1, :-1]
    
    data.append((x, y, z))
    
# generate title
titles = ["frame nr {}".format(frame) for frame in range(len(data))]


def func(frame, ax, data, titles):

    ax.pcolormesh(*data[frame])
    ax.set_title(titles[frame])
    
    return ax


fig = plt.figure()
ax = fig.add_subplot(111)

frames = range(len(data))
ani = animation.FuncAnimation(fig, func, frames, interval=300,
                              repeat_delay=1000, blit=False,
                              fargs=(ax, data, titles))

0

我这里不会提供完整的解决方案,但是使用这些指针,您应该能够得到您想要的:

您需要在函数update_line中包含一行代码,这应该是在Python代码中(而不是在您的帖子中)。这行代码应该在每次迭代此函数时设置图形的标题。 plt.title() 可以很好地实现此目的。


你觉得这是“作业”吗?玩得不错;-)(这是为了一篇论文。) - trolle3000

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