Skip to content

Step-by-step simulations with plt.pause ​

In Basthon, plt.pause now animates Matplotlib figures: a loop can show a simulation being built step by step, in the console as in the notebook.

Plot, pause, repeat. plt.pause(t) updates the figure then waits t seconds. It is the simplest way to animate a chart, with no animation function to write: add a point, pause, and so on. For instance, to simulate a radioactive decay with dice (at each throw, the dice showing a 6 are removed):

python
import random
import matplotlib.pyplot as plt

remaining = 1000
plt.axis([0, 30, 0, 1000])
for n in range(31):
    plt.scatter(n, remaining, color="tab:red")
    plt.pause(0.2)
    remaining = sum(1 for _ in range(remaining) if random.random() >= 1 / 6)
plt.show()

Until now, this kind of program, common in physics, chemistry, biology or mathematics classes, only showed the figure at the end, as many times as it paused, or even failed. The figure is now updated at each pause, while the program runs, and it is shown only once. Once the program has ended, it is interactive again: zoom, pan, download.

A radioactive decay simulation running in the notebook

The gallery has two new examples: a notebook with this simulation and a random estimation of π (Monte Carlo method), and its version for the console. The details are in the Matplotlib documentation.

See the simulations