问题描述
我正在尝试同时对两个matplotlib图形进行动画处理。我编写了一个脚本,该脚本创建了两个matplotlib.animation.FuncAnimation实例,但是只有其中一个动画,另一个保持静态。
I'm trying to animate two matplotlib figures at the same time. I wrote a script that creates two instances of matplotlib.animation.FuncAnimation, but only one of them animates, the other remains static.
这是一个最小的工作示例:
Here's a minimum working example:
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
x=np.linspace(-np.pi,np.pi,100)
# Function for making figures
def makeFigure():
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
# Plot a line
line,=ax.plot(x,np.sin(x))
return fig,ax,line
# Frame rendering function
def renderFrame(i,line):
# Apply a phase shift to the line
line.set_data(x,np.sin(x-i*2*np.pi/100))
return line,
# Make the figures
figcomps1=makeFigure()
figcomps2=makeFigure()
# Animate the figures
for figcomps in [figcomps1,figcomps2]:
fig,ax,line=figcomps
anim=animation.FuncAnimation(fig,renderFrame,fargs=[line])
plt.show()
FuncAnimation能够同时对两个数字进行动画处理吗?如果没有,是否还有另一种方法可以同时对两个matplotlib图形进行动画处理?
Is FuncAnimation capable of animating two figures simultaneously? If not, is there another way to simultaneously animate two matplotlib figures?
推荐答案
问题原因
您必须通过保留对每个对象的引用来分别跟踪每个 FuncAnimation
对象。
Cause of Issue
You must track each FuncAnimation
object separately by holding reference to each individual object.
在您的 for
循环中, FuncAnimation
对象被实例化两次(名称为 anim
),因此在命名空间中有效地覆盖了。
In your for
loop, the FuncAnimation
object is being instantiated twice (with name anim
), and hence in the namespace, effectively 'overwritten'.
来自
示例解决方案
相反,跟踪两个 FuncAnimation
对象,例如 FuncAnimation
对象,将允许它们都使用自己的计时器进行动画处理
Example Solution
Instead, tracking both FuncAnimation
objects in, for example a list of FuncAnimation
objects, will allow them to both be animated with their own timers
#...
# List of Animation objects for tracking
anim = []
# Animate the figures
for figcomps in [figcomps1,figcomps2]:
fig,ax,line=figcomps
anim.append(animation.FuncAnimation(fig,renderFrame,fargs=[line]))
我想强调的只是一个例子,因为还有许多其他方法可以在中跟踪
循环,如此问题
I wish to stress this is only an example, as there are many other methods of tracking multiple objects in a for
loop, as explored in this question
这篇关于使用matplotlib同时对两个或多个图形进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!