Python: Add dynamic text in Matplotlib animation

Question:

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.

import matplotlib.animation as animation
from PIL import Image
from IPython.display import HTML
import matplotlib.pyplot as plt

folderName = "hogehoge"
picList = glob.glob(folderName + "*.npy")

fig = plt.figure()
ims = []
 
for i in range(len(picList)):
    plt.text(10, 10, i) # This does not add the text properly
    tmp = Image.fromarray(np.load(picList[i]))
    ims.append(plt.imshow(tmp))     
 
ani = animation.ArtistAnimation(fig, ims, interval=200)
HTML(ani.to_jshtml())
Asked By: TFC

||

Answers:

You have also to add the text object to the list of artists for each frame:

import matplotlib.animation as animation
from PIL import Image
from IPython.display import HTML
import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots()
ims = []
for i in range(10):
    artists = ax.plot(np.random.rand(10), np.random.rand(10))
    text = ax.text(x=0.5, y=0.5, s=i)
    artists.append(text)
    ims.append(artists)
    
ani = animation.ArtistAnimation(fig, ims, interval=200)
HTML(ani.to_jshtml())
Answered By: jjsantoso
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.