1

I've been facing some issues trying to animate a plot with several different subplots in it. Here's a MWE:

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

data=np.random.rand(4, 50, 150)
Z=np.arange(0,120,.8)

fig, axes = plt.subplots(2,2)

it=0
for nd, ax in enumerate(axes.flatten()):
    ax.plot(data[nd,it], Z)

def run(it):
    print(it)
    for nd, ax in enumerate(axes.flatten()):
        ax.plot(data[nd, it], Z)
    return axes.flatten()

ani=animation.FuncAnimation(fig, run, frames=np.arange(0,data.shape[1]), interval=30, blit=True)
ani.save('mwe.mp4')

As you can see I'm trying to plot pre-generated data with FuncAnimation(). From the approaches I've seen this should work, however, it outputs a blank .mp4 file about a second long and gives out no error, so I have no idea what's going wrong.

I've also tried some other approaches to plotting with subplots (like this one) but I couldn't make it work and I thought this approach of mine would be simpler.

Any ideas?

TomCho
  • 3,204
  • 6
  • 32
  • 83

1 Answers1

1

You would want to update the lines instead of plotting new data to them. This would also allow to set blit=False, because saving the animation, no blitting is used anyways.

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

data=np.random.rand(4, 50, 150)
Z=np.arange(0,120,.8)

fig, axes = plt.subplots(2,2)

lines=[]

for nd, ax in enumerate(axes.flatten()):
    l, = ax.plot(data[nd,0], Z)
    lines.append(l)

def run(it):
    print(it)
    for nd, line in enumerate(lines):
        line.set_data(data[nd, it], Z)
    return lines


ani=animation.FuncAnimation(fig, run, frames=np.arange(0,data.shape[1]), 
                            interval=30, blit=True)
ani.save('mwe.mp4')

plt.show()
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712