stefanbschneider
stefanbschneider

Reputation: 6086

Matplotlib ArtistAnimation showing multiple elements in one step

I've been using matplotlib for a while to create plots but have just now discovered the animation options. I want to show a series of plots (not just individual elements) in an animation using animation.ArtistAnimation.

Unfortunately, I can't get it to animate multiple plotted elements at a time. Here's a minimal example to explain what I mean:

import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()

ims = []
for _ in range(10):
    im1, = plt.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)])
    im2, = plt.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)])
    ims.append((im1,))
    ims.append((im2,))
ani = animation.ArtistAnimation(fig, ims)

ani.save('im.mp4')

This randomly generates two lines im1, im2 10x. I always want to see both im1 and im2 at the same time. But this only shows one line at a time. If I comment ims.append((im1,)), the background is full of static lines, but it still just animates one line. I also tried to combine im1 and im2 using im1 + im2 or [im1, im2], but both lead to errors.

Extra question: Is there any reason why blit=False by default? I thought, it's supposed to improve performance?

Upvotes: 2

Views: 1476

Answers (1)

Guimoute
Guimoute

Reputation: 4629

The solution is simply to add both artists to the list at once.

The documentation talks about "a collection of artists that represent what needs to be enabled on each frame", so what ims needs to be is a list of lists (one per frame) of artists (any per frame).

import random
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig = plt.figure()

ims = []
for _ in range(10):
    im1, = plt.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)])
    im2, = plt.plot([random.randrange(10), random.randrange(10)], [random.randrange(10), random.randrange(10)])
    ims.append([im1, im2])
ani = animation.ArtistAnimation(fig, ims)

ani.save('im.mp4')

Upvotes: 3

Related Questions