2

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?

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.