首页 > 解决方案 > Python:在 Matplotlib 动画中添加动态文本

问题描述

我从保存为 numpy 数组的图像列表中制作了动画。然后我想在动画中添加一个文本,就像一个字幕一样,它的文本会随着每一帧的变化而变化,但放置plt.text(some_string)只会在第一次迭代时添加字符串,如果我在循环中更改传递的字符串,它就不起作用。下面是我的尝试。请注意 HTML 仅适用于 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())

标签: pythonmatplotlib

解决方案


您还必须将文本对象添加到每一帧的艺术家列表中:

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

推荐阅读