python - 如何使用 matplotlib 显示两个动画图
问题描述
我想在 python 中使用 matplotlib 为两个不同的图制作动画,但一切都不顺利。
我从一个情节开始,这很好。动画很容易。但现在我想添加第二个动画线图,我很挣扎。我想要第二个情节上的三行。我需要一个带有两个子图的图形吗?还是我需要有两个数字,并有一个子图来代表第二个数字上的三行中的每一行?
我想我需要创建两个动画并引入子图:
fig, axs = plt.subplots(1,2)
animation1 = FuncAnimation(fig, self.animate_first, numframes, repeat = False, interval = 10, blit = True)
animation2 = FuncAnimation(fig, self.animate_linegraph, numframes, repeat = False, interval = 10, blit = True)
但是如果 subplots 返回单个图形对象,并且这是 FuncAnimation 的第一个参数,那么动画回调函数应该做什么?当我只有一个要显示的图时,我从 animate 函数返回了补丁列表。但是当我有两个情节要更新时。我不知道该怎么办。
任何指针都非常感谢。哦(如果不是很明显:)),我对 python 完全陌生。
谢谢,保罗
解决方案
我过去按照以下方式实现了子图动画:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
# initialization function: plot the background of each frame
def init():
fig = plt.figure()
ax2 = fig.add_subplot(2, 1, 1)
ax3 = fig.add_subplot(2, 1, 2)
title = plt.title('')
title.set_text('')
return fig,ax2,ax3,title
# animation function. This is called sequentially
def animate(i):
a = ax2.pcolor(x,y,data)
b = ax3.pcolor(x2,y2,data2)
main_title.set_text('Main Title')
title2.set_text('Sub title 1')
title3.set_text('Sub title 2')
return main_title, title2, title3, ax2, ax3
# call the animator.
fig = plt.figure()
ax2 = fig.add_subplot(2, 1, 1)
ax3 = fig.add_subplot(2, 1, 2)
title2 = ax2.set_title('')
title3 = ax3.set_title('')
main_title = fig.suptitle('')
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=101, interval=250, blit=False)
anim.save('file.mp4', writer=writer)
plt.close()
不确定这是否有帮助,它主要是从我有一段时间没有使用过的旧脚本中复制和粘贴...
推荐阅读
- node.js - Lighthouse / Chrome Launcher 错误:环境变量 CHROME_PATH 必须设置为 Chromium 版本 54.0 或更高版本的可执行文件
- c++ - 如何使用具有用户定义类型的 C++ 20 范围视图
- github - 如何在 GitHub 的存储库中创建文件夹?
- google-analytics - 如何使用本地文件路径 (file://) 在基于 webview 的混合应用程序中启用 GA4 + GTM?
- java - JavaFX CSS 未部署
- java - 在 IntelliJ 上使用 Gradle 创建 JAR 文件时出错
- python - 如何使用 PyCharm CE 中的程序在终端中自动输入密码?
- css - 悬停时更改菜单文本
- python - Anaconda3 和 windows 的 nbdev_build_lib 错误
- python - 输出只在python中使用占位符0