【问题标题】:How to add time-varying title for Python matplotlib.animation?如何为 Python matplotlib.animation 添加随时间变化的标题?
【发布时间】:2022-01-24 07:51:19
【问题描述】:

我很抱歉我的英语不好。 我有一个矩阵datas(10000 乘以 5000)。它包括10000个数据案例,每个数据的维度是5000。 我想制作一个动画来一个接一个地显示每个数据。

遵循代码 1 效果很好。

(代码 1)

import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()
ims = []

for i in range(10000):
    im = plt.plot(masks[i,:])    
    ims.append(im)

ani = animation.ArtistAnimation(fig, ims, interval=10)
plt.show()
ani.save('output.mp4', writer="ffmpeg")

我想添加时变标题,以知道在某个时间显示了哪些数据(数据索引)。

我写了以下代码2

(代码 2)

import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
ims = []

for i in range(10000):
    im = plt.plot(masks[i,:])    
    tl = 'Data number:' + str(i+1) # ***added***
    plt.title(tl) # ***added*** 
    ims.append(im)

ani = animation.ArtistAnimation(fig, ims, interval=10)
plt.show()
ani.save('output.mp4', writer="ffmpeg")

但是,我得到了一个动画,其标题始终为“数据编号:10000”。

如何编写代码来添加随时间变化的标题? 我在im = plt.plot(masks[i,:]) 之前写了plt.title(tl),但没有任何改变。感谢您的帮助。

我的环境是;

  • Python 3.6.9
  • matplitlib 3.3.3

【问题讨论】:

    标签: python matplotlib animation ffmpeg


    【解决方案1】:

    我们可以通过注解一个坐标轴对象来模仿图形标题:

    #test data generation
    import numpy as np
    np.random.seed(123)
    masks = np.random.randn(10, 15)
    
    #the animation routine starts here
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    fig, ax = plt.subplots()
    ims = []
    
    #iterating over the array
    for i in range(masks.shape[0]):
        #obtaining the Line2D object representing the line plot
        im, = ax.plot(masks[i,:], color="blue") 
        #creating a centered annotation text above the graph
        ann = ax.annotate(f"This is frame {i:.0f}.", (0.5, 1.03), xycoords="axes fraction", ha="center")
        #collecting both objects for the animation
        ims.append([im, ann])
    
    ani = animation.ArtistAnimation(fig, ims, interval=300, repeat=False)
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 2014-11-19
      • 1970-01-01
      • 1970-01-01
      • 2022-07-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多