Categories
Python Answers

How to animate a scatter plot with Python matplotlib?

Spread the love

Sometimes, we want to animate a scatter plot with Python matplotlib.

In this article, we’ll look at how to animate a scatter plot with Python matplotlib.

How to animate a scatter plot with Python matplotlib?

To animate a scatter plot with Python matplotlib, we can use the celluloid package.

To install it, we run

pip install celluloid

Then we use it by writing

import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from celluloid import Camera

numpoints = 10
points = np.random.random((2, numpoints))
colors = cm.rainbow(np.linspace(0, 1, numpoints))
camera = Camera(plt.figure())
for _ in range(100):
    points += 0.1 * (np.random.random((2, numpoints)) - .5)
    plt.scatter(*points, c=colors, s=100)
    camera.snap()
anim = camera.animate(blit=True)
anim.save('scatter.mp4')

to create random points with np.random.random.

Then we call cm.rainbow to assign color to the points.

Then we create the celluloid Camera object with the plt plots.

Next, we create a for loop and move the points in the loop with

points += 0.1 * (np.random.random((2, numpoints)) - .5)

Then we create a scatter plot of the points with

plt.scatter(*points, c=colors, s=100)

Next we call camera.snap() to snap a frame of the current plot.

Then we call `camera.animate to animate the frames.

And we call save to save the file as scatter.mp4.

Conclusion

To animate a scatter plot with Python matplotlib, we can use the celluloid package.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *