2

I am simulating a differential equation evolving in time in a Python Jupyter notebook using the script below:

import numpy as np
import matplotlib.pyplot as plt
from IPython.display import clear_output

L = 100
x_positions = np.linspace(0, L, 1001)
for t in range(1, 100):
    mass = np.zeros(1001)
    plt.ioff()
    for n in range(-5, 5):
        mass += [np.exp(-(x + 2 * n * L) ** 2 / (4 * t)) for x in x_positions]
    plt.scatter(mass, x_positions)
    clear_output()
    plt.show()
    plt.pause(0.1)

However, the Jupyter notebook cell refreshes each time the plot updates, which creates unnecessary scrolling and blinking. Is there a better way to prevent this behavior?

Jbag1212
  • 167
  • 1
  • 5
  • Other alternatives are illustrated [here](https://github.com/fomightez/animated_matplotlib-binder). On that page click 'launch binder' and step through running the cells discussing various ways. There's links to more complex ways towards the bottom. I especially like the player with a controller widget that you can generate & that still works in nbviewer for sharing with non-coders. See [example here](https://nbviewer.org/gist/fomightez/d862333d8eefb94a74a79022840680b1). – Wayne Jun 17 '23 at 16:21

1 Answers1

2

Using clear_output(wait=True) will do the trick at the cost of a small speed loss.

2lian
  • 36
  • 4
  • Great, thank you. Do you know any way to fix the y-axis? It keeps rescaling. – Jbag1212 Jun 17 '23 at 02:36
  • 1
    You need to fix the axis before the `plt.show()` in every loop. See this post: https://stackoverflow.com/a/25421861/22081626 – 2lian Jun 17 '23 at 02:44