'How to add time-varying title for Python matplotlib.animation?

I am sorry for my poor English. I have a matrix datas (10000 times 5000). It includes 10000 cases of data and the dimension of each data is 5000. I want to make an animation to show each data one after another.

Following Code 1 works well.

(Code 1)

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ims = []

for i in range(10000):
    im = plt.plot(masks[i,:])    
    ims.append(im)

ani = animation.ArtistAnimation(fig, ims, interval=10)
plt.show()
ani.save('output.mp4', writer="ffmpeg")

I want to add the time-varying title to know which data (data index) is shown at a certain time.

And I wrote the following Code 2.

(Code 2)

import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ims = []

for i in range(10000):
    im = plt.plot(masks[i,:])    
    tl = 'Data number:' + str(i+1) # ***added***
    plt.title(tl) # ***added*** 
    ims.append(im)

ani = animation.ArtistAnimation(fig, ims, interval=10)
plt.show()
ani.save('output.mp4', writer="ffmpeg")

However, I got an animation whose title is always 'Data number: 10000'.

How can I write the code to add the time-varying title? I wrote plt.title(tl) before im = plt.plot(masks[i,:]) but nothing changed. Thank you for your help.

My environments are;

  • Python 3.6.9
  • matplitlib 3.3.3


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source