Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib animation erase previous data [duplicate]

I am trying to make a simple animation with Matplotlib to check that my simulation runs well. I want to see how two particles move in the x-y plane: if the code works, they should attract and end in the same point or close in space.

I compute the positions of the particles inside a 'for' loop and each time I get the positions, I plot them using plt.scatter(x, y), where x and y are the positions at time t = t + dt. I have read online that I can write plt.pause(0.05) inside the loop and this will produce the simple animation I am looking for.

An example of my code is the following:

import numpy as np
import matplotlib.pyplot as plt

for k in range(steps):
    pos = computeNewPos(pos, vel, force)        

    plt.scatter(pos[0, 0], pos[0, 1], label = '1', color = 'r')
    plt.scatter(pos[1, 0], pos[1, 1], label = '2', color = 'b')

    plt.xlabel('X')
    plt.ylabel('Y')

    plt.pause(0.05)

plt.show()

This works, but the 'animation' I get contains old data points and I would like to only see the updated position. This will make it easier to keep track of where the particles are. How can I 'erase' the old points for each run inside the for loop? Is there a way of clearing the frame at each run?

like image 781
ma7642 Avatar asked Nov 17 '25 09:11

ma7642


1 Answers

The simplest solution (if perhaps not the most efficient) is to wipe the axis with axis.clear() before redrawing:

fig, ax = plt.subplots()
for k in range(steps):
    pos = computeNewPos(pos, vel, force)
    ax.clear()        

    ax.scatter(pos[0, 0], pos[0, 1], label = '1', color = 'r')
    ax.scatter(pos[1, 0], pos[1, 1], label = '2', color = 'b')

    ax.xlabel('X')
    ax.ylabel('Y')

    plt.pause(0.05)

plt.show()

Note that I'm generating the figure and axis in the beginning (so it still work with multiple windows open). You could also use plt.gca().clear() to clear the current axis, but that's IMO more brittle and prone to error.

like image 143
GPhilo Avatar answered Nov 20 '25 00:11

GPhilo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!