0

I am trying to generate an animation of this plot with FuncAnimation. Those lines change over time, and that's what I would like to capture with FuncAnimation.

Currently, I can generate an animation, but one single line per subplot.

My code for animation roughly looks like this:

y1 = np.random.rand(1000, 5, 80)
y2 = np.random.rand(1000, 5, 80)
fig, axes = plt.subplots(1 ,2)
lines = []
x = np.linspace(0, 1, 1000)

for index, ax in enumerate(axes.flatten()):
   if index == 0:
      l, = ax.plot(y1[:,0,0], x)
   if index == 1:
      l, = ax.plot(y2[:,0,0], x)
   lines.append(l)

def run(it):
    for index, line in enumerate(lines):
        if index == 0:
           line.set_data(x, y1[:, 0, it]
        if index == 1:
           line.set_data(x, y2[:, 0, it]
    return lines

ani = animation.FuncAnimation(fig, run, frames =80)
plt.show()

But, again, that code only generates only line per subplot. I'd like to have multiple lines per subplot (in the example code, that would be 5 lines). Does anyone know how do that? I don't have to use my code template, it could be something entirely different.

Schach21
  • 412
  • 4
  • 21
  • https://stackoverflow.com/questions/49165233/two-lines-matplotib-animation#49168311 The answer is here. – Schach21 Sep 25 '20 at 02:30

1 Answers1

0

I've adapted the matplotlib animation example:

You can see which lines I've added/changed in the comments.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, (ax, ax2) = plt.subplots(2) #create two axes
xdata, ydata = [], []
ln, = ax.plot([], [], 'ro')
ln2, = ax2.plot([], [], 'go') # added

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    ax2.set_xlim(0, 2*np.pi) # added
    ax2.set_ylim(-1, 1) # added
    return ln,ln2 # added ln2

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    ln2.set_data(xdata, ydata) # added
    return ln, ln2 #added ln2

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()
mullinscr
  • 1,668
  • 1
  • 6
  • 14
  • But that's still generating one line per subplot. What I want is to generate a plot of let's say sin and cos in the same subplot. For instance, subplot (1, 2, 1) I want to plot sin(x) and cos(x) and subplot(1, 2, 2) I want to plot some other functions. – Schach21 Sep 25 '20 at 01:10