如何在Matplotlib中将两个动画绘制在同一张图中?

3
在下面的代码中,我有两个单独的动画,并将它们绘制在两个单独的子图中。我希望它们都在一个单独的图中运行,而不是现在这样。我尝试了下面解释的方法,但是它会导致问题,请求帮助。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time as t

x = np.linspace(0,5,100)

fig = plt.figure()
p1 = fig.add_subplot(2,1,1)
p2 = fig.add_subplot(2,1,2)

def gen1():
    i = 0.5
    while(True):
        yield i
        i += 0.1


def gen2():
    j = 0
    while(True):
        yield j
        j += 1


def run1(c):
    p1.clear()
    p1.set_xlim([0,15])
    p1.set_ylim([0,100])

    y = c*x
    p1.plot(x,y,'b')

def run2(c):
    p2.clear()
    p2.set_xlim([0,15])
    p2.set_ylim([0,100])

    y = c*x
    p2.plot(x,y,'r')

ani1 = animation.FuncAnimation(fig,run1,gen1,interval=1)
ani2 = animation.FuncAnimation(fig,run2,gen2,interval=1)
fig.show()

我试图创建一个单独的子图,而不是 p1p2,并在该单个子图中绘制这两个图。也就是只绘制一个图而不是两个。据我所知,这是因为其中一个在绘制后立即被清除了。如何解决这个问题呢?
1个回答

6
由于您没有展示实际产生问题的代码,因此很难确定问题出在哪里。
但是为了回答如何在同一个坐标轴(subplot)中动画两条线的问题,我们可以摆脱clear()命令并更新这些线,而不是为每个帧生成一个新图(这样更有效率)。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

x = np.linspace(0,15,100)

fig = plt.figure()
p1 = fig.add_subplot(111)

p1.set_xlim([0,15])
p1.set_ylim([0,100])

# set up empty lines to be updates later on
l1, = p1.plot([],[],'b')
l2, = p1.plot([],[],'r')

def gen1():
    i = 0.5
    while(True):
        yield i
        i += 0.1

def gen2():
    j = 0
    while(True):
        yield j
        j += 1

def run1(c):
    y = c*x
    l1.set_data(x,y)

def run2(c):
    y = c*x
    l2.set_data(x,y)

ani1 = animation.FuncAnimation(fig,run1,gen1,interval=1)
ani2 = animation.FuncAnimation(fig,run2,gen2,interval=1)
plt.show()

非常感谢!这个可行。为了确保我今后正确发布问题,您能否澄清一下您所说的“我没有提供实际产生问题的代码”是什么意思?我在这里发布了整个程序。我应该添加什么? - Ananda
当然。您在此发布的代码运行良好。它有两个子图,都按预期更新。但是,您正在询问使用不同代码时出现的问题,即“创建单个子图而不是p1和p2”。但是,创建此单个子图的代码仍然未知-因此很难说在这种情况下出了什么问题。 - ImportanceOfBeingErnest

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接