简体   繁体   English

matplotlib中带有子图的动画图

[英]Animated plot with subplots in matplotlib

I've been facing some issues trying to animate a plot with several different subplots in it. 我一直在尝试为具有多个不同子图的图制作动画时遇到一些问题。 Here's a MWE: 这是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')

As you can see I'm trying to plot pre-generated data with FuncAnimation() . 如您所见,我正在尝试使用FuncAnimation()绘制预生成的数据。 From the approaches I've seen this should work, however, it outputs a blank .mp4 file about a second long and gives out no error, so I have no idea what's going wrong. 从我已经看到的方法来看,这应该可行,但是,它输出一个空白的.mp4文件大约一秒钟,并且没有发出错误,所以我不知道出了什么问题。

I've also tried some other approaches to plotting with subplots (like this one ) but I couldn't make it work and I thought this approach of mine would be simpler. 我还尝试了一些其他方法来绘制子图(例如这种图 ),但是我无法使其起作用,我认为我的这种方法会更简单。

Any ideas? 有任何想法吗?

You would want to update the lines instead of plotting new data to them. 您可能希望更新这些行,而不是向它们绘制新数据。 This would also allow to set blit=False , because saving the animation, no blitting is used anyways. 这也将允许设置blit=False ,因为保存动画时,无论如何都不会使用斑点。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM