Skip to content Skip to sidebar Skip to footer

Update X Value Using Slider Matplotlib

I try to draw a graph, which show the progress of a chemical reaction. The progress itself (time or reactionsteps) should be changeable using a slider. The code I have so far: impo

Solution 1:

Assuming you have time on the x-axis and want to change the maximum time of your plot that is created by the same function every time, I came up with this:

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('Reaktionsfortschritt')

t0 = 0
t = np.arange(0, t0, .5)
k0 = 0.17
a = np.exp(- k0 * t)

l, = ax.plot(t, a, lw=3, color='crimson')
plt.axis([0, 20, 0, 1])

axrs = plt.axes([0.25, 0.1, 0.65, 0.03])
srs = Slider(axrs, 'Reaktionsschritte', 0, 20, valinit=0)

defupdate(x):
    t0 = x
    t = np.arange(0, t0, .5)
    ax.lines.pop(0)  # remove previous line plot
    ax.plot(t, np.exp(- k0 * t), lw=3, color='crimson')  # plot new one
    fig.canvas.draw()

srs.on_changed(update)

plt.show()

See what it does when changing the Slider value and let me know if this is what you wanted it to do.


To your edit: When you add a second plot, you have two lines objects. Try to print ax.lines directly after you run the code (before touching the Slider) and see that it really is a list of two lines. Then call ax.lines.pop(0) and see that one element is popped from the list. That's what the above code does, it removes lines from the axes object ax every time you touch the Slider (because then update is called), which after calling fig.canvas.draw() leads to vanishing of previous plots. If you now touch the Slider once, then two new lines are added to ax and only one is removed. This is why you think there is no going back. So if you now added a second plot, you just have to pop twice from the list ax.lines with ax.lines.pop(0) and the code works fine ;-)

Post a Comment for "Update X Value Using Slider Matplotlib"