Ananda
Ananda

Reputation: 3272

How do I plot two animations in a single plot with matplotlib?

In the following code I have two separate animations and I have plotted them in a two separate subplots. I want both of them to run in a single plot instead of this. I have tried the approach explained below but it is giving me issues as explained below. Please help

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

I tried creating a single subplot instead of p1 and p2 and have both the plots graphed in that single subplot. That is just plotting one graph and not both of them. As far as I can say it is because one of them is getting cleared right after it is plotted.

How do I get around this problem?

Upvotes: 3

Views: 8207

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

As you do not show the code that is actually producing the problem, it's hard to tell where the problem lies.

But to answer the question of how to animate two lines in the same axes (subplot), we can just get rid of the clear() command and update the lines, instead of producing a new plot for every frame (which is more efficient anyways).

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

Upvotes: 6

Related Questions