Reputation: 82
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;
Upvotes: 0
Views: 566
Reputation: 12410
We can imitate the figure title by annotating an axes object:
#test data generation
import numpy as np
np.random.seed(123)
masks = np.random.randn(10, 15)
#the animation routine starts here
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
ims = []
#iterating over the array
for i in range(masks.shape[0]):
#obtaining the Line2D object representing the line plot
im, = ax.plot(masks[i,:], color="blue")
#creating a centered annotation text above the graph
ann = ax.annotate(f"This is frame {i:.0f}.", (0.5, 1.03), xycoords="axes fraction", ha="center")
#collecting both objects for the animation
ims.append([im, ann])
ani = animation.ArtistAnimation(fig, ims, interval=300, repeat=False)
plt.show()
Upvotes: 1