0

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

1 Answer 1

1

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())
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.