【问题标题】:How do I plot two animations in a single plot with matplotlib?如何使用 matplotlib 在一个图中绘制两个动画?
【发布时间】:2017-01-10 16:49:04
【问题描述】:

在下面的代码中,我有两个单独的动画,我将它们绘制在两个单独的子图中。我希望他们两个都在一个情节中运行,而不是这个。我已经尝试过下面解释的方法,但它给了我如下所述的问题。请帮忙

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,并将两个图都绘制在该单个子图中。那只是绘制一个图表,而不是两者。据我所知,这是因为其中一个在绘制后立即被清除。

我该如何解决这个问题?

【问题讨论】:

    标签: animation matplotlib graph


    【解决方案1】:

    由于您没有显示实际产生问题的代码,因此很难判断问题出在哪里。

    但要回答如何在同一轴(子图)中为两条线设置动画的问题,我们可以摆脱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()
    

    【讨论】:

    • 非常感谢!这是有效的。为确保我正确发布未来的问题,您能否澄清您的意思是我没有提供实际产生问题的代码?我在这里发布了整个程序。我还应该添加什么?
    • 当然。您在此处发布的代码运行良好。它有两个子图,并且都按预期更新。但是,您询问的是使用不同代码时发生的问题,即“创建单个子图而不是 p1 和 p2”。但是创建这个单一子图的代码仍然未知——因此很难说在这种情况下出了什么问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-12
    • 2018-02-24
    • 2019-08-21
    • 2018-02-08
    • 2019-05-10
    • 2011-10-15
    相关资源
    最近更新 更多