I made an animation from the list of images saved as numpy arrays.
Then I want to add a text onto the animation like like a subtitle whose text changes for each frame but placing plt.text(some_string)
only adds the string at the first iteration and it does not work if I change the passed string in the loop. Below is my attempt. Please note HTML is just for Jupyter Lab.
JavaScript
x
19
19
1
import matplotlib.animation as animation
2
from PIL import Image
3
from IPython.display import HTML
4
import matplotlib.pyplot as plt
5
6
folderName = "hogehoge"
7
picList = glob.glob(folderName + "*.npy")
8
9
fig = plt.figure()
10
ims = []
11
12
for i in range(len(picList)):
13
plt.text(10, 10, i) # This does not add the text properly
14
tmp = Image.fromarray(np.load(picList[i]))
15
ims.append(plt.imshow(tmp))
16
17
ani = animation.ArtistAnimation(fig, ims, interval=200)
18
HTML(ani.to_jshtml())
19
Advertisement
Answer
You have also to add the text object to the list of artists for each frame:
JavaScript
1
17
17
1
import matplotlib.animation as animation
2
from PIL import Image
3
from IPython.display import HTML
4
import matplotlib.pyplot as plt
5
import numpy as np
6
7
fig, ax = plt.subplots()
8
ims = []
9
for i in range(10):
10
artists = ax.plot(np.random.rand(10), np.random.rand(10))
11
text = ax.text(x=0.5, y=0.5, s=i)
12
artists.append(text)
13
ims.append(artists)
14
15
ani = animation.ArtistAnimation(fig, ims, interval=200)
16
HTML(ani.to_jshtml())
17