Reputation: 11
I have been trying to graph a function with two parameters that can be varied to see different behavior. I would like to use a slider to vary the parameters.
In my search I have come across sliders that change the axes but not parts of a mathematical function.
So I have the following code which should work if my two parameters Gmax and Km were the axes:
from matplotlib.widgets import Slider
import numpy as np
Gmax=1
Km= 1
def f(S):
s1 = Gmax*S #G_max
e1 = S + Km #K_m
return divide(s1,e1)
S=arange(0,100,0.1)
ax = subplot(111)
subplots_adjust(left=0.15, bottom=0.25)
l = plot(f(S))
grid(False)
title('Playing with sliders')
xlabel('time')
ylabel('concentration')
axcolor = 'lightgoldenrodyellow'
axGmax = axes([0.15, 0.1, 0.65, 0.03], axisbg=axcolor)
axKm = axes([0.15, 0.15, 0.65, 0.03], axisbg=axcolor)
sGmax = Slider(axGmax, 'Gmax', 0.1, 3.0, valinit=1)
sKm = Slider(axKm, 'Km', 0.01, 1.0, valinit=1)
def update(val):
s1 = Gmax*S * sGmax.val
e1 = S + Km * sKm.val
l.set_ydata(y)
ax.set_ylim(y.min(), y.max())
draw()
sGmax.on_changed(update)
sKm.on_changed(update)
show()
So I guess my question is if there is a command for parameters instead of the ax command for axes sliders? Or if there is another way of doing it?
Upvotes: 1
Views: 4736
Reputation: 97291
Your code is almost right, but you should change l = plot(f(S))
to l, = plot(f(S))
because plot() returns a list. Then you can call l.set_ydata(...)
to set the new value.
Here is the code:
import matplotlib.pyplot as plt
import pylab
import numpy as np
def f(S, Gmax, Km):
s1 = Gmax*S # G_max
e1 = S + Km # K_m
return np.divide(s1, e1)
def update(val):
l.set_ydata(f(S, sGmax.val, sKm.val))
S = np.arange(0, 100, 0.1)
ax = plt.subplot(111)
plt.subplots_adjust(left=0.15, bottom=0.25)
l, = plt.plot(f(S, 1.0, 1.0))
plt.grid(False)
plt.title('Playing with sliders')
plt.xlabel('time')
plt.ylabel('concentration')
axcolor = 'lightgoldenrodyellow'
axGmax = plt.axes([0.15, 0.1, 0.65, 0.03], facecolor=axcolor)
axKm = plt.axes([0.15, 0.15, 0.65, 0.03], facecolor=axcolor)
sGmax = pylab.Slider(axGmax, 'Gmax', 0.1, 3.0, valinit=1)
sKm = pylab.Slider(axKm, 'Km', 0.01, 1.0, valinit=1)
sGmax.on_changed(update)
sKm.on_changed(update)
plt.show()
Upvotes: 3