如何在matplotlib中制作两个滑块

时间:2017-04-12 23:57:20

标签: python matplotlib slider odeint

我想在matplotlib中制作两个滑块来手动更改捕食者 - 猎物模型中的N和P值:

new_list

这是我的代码,它生成N和P的固定初始值的图表。但是,我想更改它们以查看绘图如何变化。为此,我想使用像http://matplotlib.org/users/screenshots.html#slider-demo这样的滑块,但我不知道如何将其添加到我的代码中......

有人可以给我任何指示吗?非常感谢!! XX

2 个答案:

答案 0 :(得分:2)

从示例中,希望这些评论可以帮助您了解其中的内容:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
from scipy.integrate import odeint

# Function to draw
def lotka(x, t, params):
    N, P = x
    alpha, beta, gamma, delta = params 
    derivs = [alpha*N - beta*N*P, gamma*N*P - delta*P] 
    return derivs

# Parameters
Nmin = 1
Nmax = 100
Pmin = 1
Pmax = 100
N0 = 2
P0 = 1
alpha = 3
beta = 0.5
gamma = 0.4
delta = 3

params = [alpha, beta, gamma, delta]
x0=[N0,P0]
maxt = 20
tstep = 0.01

# Initial function values
t = np.arange(0, maxt, tstep)
prey, predator = odeint(lotka, x0, t, args=(params,)).T
# odeint returne a shape (2000, 2) array, with the value for
# each population in [[n_preys, n_predators], ...]
# The .T at the end transponses the array, so now we get each population
# over time in each line of the resultint (2, 2000) array.

# Create a figure and an axis to plot in:
fig = plt.figure()
ax = fig.add_axes([0.10, 0.3, 0.8, 0.6])
prey_plot = ax.plot(t, prey, label="Prey")[0]
predator_plot = ax.plot(t, predator, label="Predator")[0]

ax.set_xlabel("Time")
ax.set_ylabel("Population size")
ax.legend(loc="upper right")
ax.set_title('Prey & Predator Static Model')
ax.grid(color="b", alpha=0.5, linestyle="dashed", linewidth=0.5)
ax.set_ylim([0, np.max([prey, predator])])

# create a space in the figure to place the two sliders:
axcolor = 'lightgoldenrodyellow'
axis_N = fig.add_axes([0.10, 0.1, 0.8, 0.03], facecolor=axcolor)
axis_P = fig.add_axes([0.10, 0.15, 0.8, 0.03], facecolor=axcolor)
# the first argument is the rectangle, with values in percentage of the figure
# size: [left, bottom, width, height]

# create each slider on its corresponding place:
slider_N = Slider(axis_N, 'N', Nmin, Nmax, valinit=N0)
slider_P = Slider(axis_P, 'P', Pmin, Pmax, valinit=P0)

def update(val):
    # retrieve the values from the sliders
    x = [slider_N.val, slider_P.val]
    # recalculate the function values
    prey, predator = odeint(lotka, x, t, args=(params,)).T
    # update the value on the graph
    prey_plot.set_ydata(prey)
    predator_plot.set_ydata(predator)
    # redraw the graph
    fig.canvas.draw_idle()
    ax.set_ylim([0, np.max([prey, predator])])

# set both sliders to call update when their value is changed:
slider_N.on_changed(update)
slider_P.on_changed(update)

# create the reset button axis (where its drawn)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
# and the button itself
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')

def reset(event):
    slider_N.reset()
    slider_P.reset()

button.on_clicked(reset)

但是,请注意,您应该shown how you tried使示例适应您的情况以及它是如何行为不端。

尽管如此,欢迎来到Stackoverflow。

答案 1 :(得分:2)

所以,我尝试过这段代码:

from scipy import integrate
from matplotlib.widgets import Slider, Button, RadioButtons

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
plt.xlabel("Time")
plt.ylabel("Population size")
plt.legend(["Prey", "Predator"], loc="upper right")

plt.title('Prey & Predator Static Model')
plt.grid(color="b", alpha=0.5, linestyle="dashed", linewidth=0.5)

l1, l2 = plt.plot(t, equation)

axcolor = 'b'
ax_N = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
ax_P = plt.axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)

sN = Slider(ax_N, 'N', 0, 80, valinit=1)
sP = Slider(ax_P, 'P', 0, 80, valinit=1)


def update(val):
    N = N*sN.val
    P = P*sP.val
    x = equation
    fig.canvas.draw_idle()
    l1, l2.set_ydata(y)    
    ax.set_ylim(y.min(), y.max())  
    draw()

sN.on_changed(update)
sP.on_changed(update)

plt.show()

我无法操纵滑块。非常感谢@ berna1111