Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

Python: Add dynamic text in Matplotlib animation

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())
question from:https://stackoverflow.com/questions/65838939/python-add-dynamic-text-in-matplotlib-animation

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...