mercredi 14 juin 2017

update random particles in matplotlib using slider

I try to make a plot of random particles, where the number of particles is decreased using a slider. So far I got the following:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider


fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
fig.canvas.set_window_title('Teilchen')

x = np.random.randn(50)
y = np.random.randn(50)

plt.plot(x,y, 'o')

axrs = plt.axes([0.125, 0.1, 0.778, 0.03], facecolor='lightblue')
srs = Slider(axrs, 'Zeit', 0, 50, valinit=0, valfmt='%0.0f')

def update1(x): 
    p = round(srs.val,0)
    n = int(50-p)
    x = np.random.randn(n)
    y = np.random.randn(n)
    plt.cla()
    ax.plot(x,y, 'o')
    fig.canvas.draw_idle()

srs.on_changed(update1)

plt.show()

The problem is that instead of redrawing the decreased number of particles, particles get added to the existing plot. The position of the remaining particles should preferably stay the same over the whole time.




Aucun commentaire:

Enregistrer un commentaire