Matplotlib animation update title using ArtistAnim

2020-02-14 18:15发布

I am trying to use the ArtistAnimation to create an animation. And everything is working, except set_title isn't working. I don't understand why blit=False doesn't work.

Do I need to go to a FuncAnimation?

no title

for time in np.arange(-0.5,2,0.01):
    writer.UpdatePipeline(time=time)

    df=pd.read_csv(outputPath + '0.csv', sep=',')
    df['x'] = 1E6*df['x']
    df['Efield'] = 1E-6*df['Efield']

    line3, = ax3.plot(df['x'], df['Efield'])

    line1A, = ax1.semilogy(df['x'], df['em_lin'])
    line1B, = ax1.semilogy(df['x'], df['Arp_lin'])

    line2A, = ax2.plot(df['x'], df['Current_em'])
    line2B, = ax2.plot(df['x'], df['Current_Arp'])

    ax1.set_title('$t = ' + str(round(time, n)))
    ims.append([line1A, line1B, line2A, line2B, line3])

im_ani = animation.ArtistAnimation(fig, ims, interval=50, blit=False)
im_ani.save(outputPath + 'lines.gif', writer='imagemagick', fps=10, dpi=100)
plt.show()

1条回答
冷血范
2楼-- · 2020-02-14 18:56

Two problems. The immeadiate is that the title is not part of the list of artists to update, hence the animation cannot know that you want to update it. The more profound problem is that there is only a single title per axes. Hence even if you include the title in the list of artists, it will always show the text that it has last been set to.

The solution would be not to use the axes' title to update, but other text elements, one per frame.

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()

enter image description here

For reference the same as FuncAnimation would look as follows, where the title can be set directly as usual.

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()
查看更多
登录 后发表回答