matplotlib 中带有子图的动画图 [英] Animated plot with subplots in matplotlib

查看:72
本文介绍了matplotlib 中带有子图的动画图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试为其中包含多个子图的动画设置动画时遇到一些问题.这是MWE:

I've been facing some issues trying to animate a plot with several different subplots in it. Here's a 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 文件并且没有给出任何错误,所以我不知道出了什么问题.

As you can see I'm trying to plot pre-generated data with 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.

我还尝试了一些其他方法来绘制子图(例如这个),但我无法让它工作我认为我的这种方法会更简单.

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.

有什么想法吗?

推荐答案

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

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.

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

这篇关于matplotlib 中带有子图的动画图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆