Search code examples
pythonmatplotlibmatplotlib-widgetmatplotlib-animation

matplotlib scatter animation in jupyterlab vanishes after initial frame


I'm have a JupyterLab notebook (v1.1.4) in which I'm trying to animate a scatter plot. I tried using the raindrops example from the matplotlib examples, and it runs fine, but I can't get mine to work.

Here's a MWE

%matplotlib widget
import random
import matplotlib.pyplot as plt
import matplotlib.animation as anim

fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
p1, p2 = [], []

points = 10
for member in range(points):
    p1.append(random.random())
    p2.append(random.random())
scat = ax.scatter(p1,p2)

def animator(i):
    for idx in range(points):
        p1[idx] = random.random()
        p2[idx] = random.random()
    scat.set_offsets([p1, p2])

animation = anim.FuncAnimation(fig, animator, 50, interval=100)

It briefly shows the first frame, but as soon as the animation fires up, I get a blank figure. The widget is still present, but it has nothing in it, not even the axes frame.


Solution

  • I tried running this in an interactive session instead of the notebook. I got the following error:

    ValueError: 'vertices' must be a 2D list or array with shape Nx2

    Turns out that the [p1,p2] list needed to be transposed. I cast this list to a numpy array and transposed it et voila.