【问题标题】:Animated plot with subplots in matplotlibmatplotlib 中带有子图的动画图
【发布时间】:2018-01-08 16:28:55
【问题描述】:

我在尝试为包含多个不同子图的情节设置动画时遇到了一些问题。这是一个 MWE:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

data=np.random.rand(4, 50, 150)
Z=np.arange(0,120,.8)

fig, axes = plt.subplots(2,2)

it=0
for nd, ax in enumerate(axes.flatten()):
    ax.plot(data[nd,it], Z)

def run(it):
    print(it)
    for nd, ax in enumerate(axes.flatten()):
        ax.plot(data[nd, it], Z)
    return axes.flatten()

ani=animation.FuncAnimation(fig, run, frames=np.arange(0,data.shape[1]), interval=30, blit=True)
ani.save('mwe.mp4')

如您所见,我正在尝试使用FuncAnimation() 绘制预先生成的数据。从我看到的方法来看,这应该可以工作,但是,它会输出一个大约一秒长的空白 .mp4 文件并且没有给出任何错误,所以我不知道出了什么问题。

我还尝试了一些其他方法来绘制子图(例如 this one),但我无法成功,我认为我的这种方法会更简单。

有什么想法吗?

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    您可能希望更新线条而不是向它们绘制新数据。这也允许设置blit=False,因为保存动画,无论如何都不会使用blitting。

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.animation as animation
    
    data=np.random.rand(4, 50, 150)
    Z=np.arange(0,120,.8)
    
    fig, axes = plt.subplots(2,2)
    
    lines=[]
    
    for nd, ax in enumerate(axes.flatten()):
        l, = ax.plot(data[nd,0], Z)
        lines.append(l)
    
    def run(it):
        print(it)
        for nd, line in enumerate(lines):
            line.set_data(data[nd, it], Z)
        return lines
    
    
    ani=animation.FuncAnimation(fig, run, frames=np.arange(0,data.shape[1]), 
                                interval=30, blit=True)
    ani.save('mwe.mp4')
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2020-09-21
      • 2016-02-01
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 2020-08-27
      • 1970-01-01
      • 2021-01-09
      相关资源
      最近更新 更多