如何在matplotlib中制作两个滑块

2023-12-06

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

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint

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

N=2
P=1
alpha=3
beta=0.5
gamma=0.4
delta=3

params = [alpha, beta, gamma, delta]
x0=[N,P]
maxt = 20
tstep = 0.01

t=np.arange(0,maxt,tstep)
equation=odeint(lotka, x0, t, args=(params,))

plt.plot(t,equation)
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)

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

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


从这个例子中,希望评论能帮助你理解什么是:

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)

但请注意,您应该有显示了您的尝试方式使示例适应您所拥有的情况以及它的错误行为。

尽管如此,欢迎来到 Stackoverflow。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在matplotlib中制作两个滑块 的相关文章

随机推荐

  • 如何在D3中添加强制拖动事件并使节点保持在我离开的位置?

    我有一个 D3 api 它显示节点之间的某种关系 我想在这里应用 force drag 事件 我将把节点拖动到某个位置并离开节点 它将留在那里 我这里有一个工作小提琴 它显示了节点之间的关系 任何人都可以帮助我从这里在这个 api 中执行此
  • Sizeof 与 Strlen

    include
  • 如何用VBA读取IE表格文本?

    我正在尝试编写 vba 代码来遵循此过程 自动填写并提交网络表单 打开一个新网页 其中包含答案http ec europa eu taxation customs vies locale en 找到新网页的地址 因为我需要阅读此内容 读取h
  • WTForms 日期验证

    我目前正在尝试使用 Flask 构建一个简单的 Web 应用程序 我也使用 WTForms 但是我在从表单获取日期信息并对其进行验证时遇到问题 这是形式 from flask wtf import FlaskForm from wtform
  • 递归文件搜索

    我试图弄清楚如何解决这个问题 出于某种原因 它在某个点结束 我不太擅长递归 我确信问题出在某个地方 另外 即使我检查了 cFileName 它仍然显示在最后 不知道为什么 但 不再出现了 void find files wstring wr
  • Swing Ui 倍增面板重影

    最近我的 swing ui 遇到了问题 一切正常 直到我从 JButton 触发工具提示 之后将鼠标移到用户界面的其余部分上会导致奇怪的伪像和故障 Bugged 我无法显示整个代码 因为它太多了 但我在这里初始化按钮 GridBagCons
  • 如何将表单数据提交到 Fancybox 中的 iframe?

    我有一个包含常规链接作为提交按钮的表单 单击此链接后 我希望将表单提交数据传输到 iframe 的 fancybox 我花了几个小时对该主题进行反复试验和研究 但毫无结果 我还在 StackOverflow 上读过这个帖子 其中详细说明了我
  • 旋转时固体物体的持续角度

    我是新来的Unity and Oculus 我有一堆图像 它们的路径和其他信息是加载自JSON file 我正在尝试在 VR 房间中渲染它 并希望为用户提供一种体验 他可以使用以下命令在该房间内移动这些图像Oculus Touch 我放置了
  • 如何将证书传递给 WSTrust 以获得 Saml 令牌

    下面是使用 WSTrustChannelFactory 获取 token 的示例 从这里 var stsBinding new WS2007HttpBinding stsBinding Security Mode SecurityMode
  • 在python中使用PIL以相同的裁剪尺寸裁剪整个图像

    我的 PIL python 逻辑有一些问题 我的目标是从左上角到右下角位置完全裁剪一张 64x64 大小的图像 我可以进行一次裁剪操作 但是当我尝试通过循环完全裁剪图像时 我被中间的循环情况卡住了 在第一个循环中 我可以裁剪 0 0 64
  • PowerMock + Emma - 私有静态方法和其他方法的代码覆盖率显示为 0% [重复]

    这个问题在这里已经有答案了 我从以下位置引用了 PowerMock 使用 PowerMockito 模拟私有方法并在这里应用了相同的逻辑 另外 我在 eclipse STS 中安装了 EMMA 开源工具 但是当我运行代码时 我看到代码覆盖率
  • 查找包含特定值的数组的文档

    如果我有这个架构 person name String favoriteFoods Array 在哪里favoriteFoods数组由字符串填充 我如何使用猫鼬找到所有将 寿司 作为他们最喜欢的食物的人 我希望得到类似的东西 PersonM
  • 使用 Pandas Groupby 和 Apply 函数时处理 None 值

    我有一个Dataframe in Pandas以一个字母和两个日期作为列 我想使用以下方法计算前一行的两个日期列之间的工作日shift 前提是Letter值是相同的 使用 groupby 我正在这样做 apply 这种方法一直有效 直到我传
  • PdfContentStreamEditor 在 PDF 文件上旋转图像

    我希望这是一个简单的问题 我正在尝试使用 iTextSharp 修改一些 PDF 文件 但是 iTextSharp 放在文件末尾的 XMP 元数据似乎破坏了 PDF 文件的布局 而且我不太熟悉 PDF 格式 完全明白为什么 You can
  • 在 ANTLR4 中使用什么来解决歧义(而不是语法谓词)?

    在 ANTLR v3 中 句法谓词可用于解决例如悬空 else 问题 ANTLR4 似乎接受具有类似歧义的语法 但在解析过程中它会报告这些歧义 例如 line 2 29 reportAmbiguity d 0 e ambigAlts 1 2
  • 列表中的矩阵相乘

    我想将列表的多个矩阵相乘 我知道这适用于单个矩阵 x1 lt c 2 2 2 3 1 2 4 6 1 2 4 y1 lt c 5 4 3 3 4 2 1 6 4 2 3 x2 lt c 8 2 7 3 1 2 2 2 1 2 6 y2 lt
  • 渐变在 IE 10/11 中不起作用

    这里我的 CSS 可以让渐变在任何浏览器中工作 包括 IE 版本 9 IE9 wrapper background moz linear gradient top 0f1925 000 repeat scroll 0 0 transpare
  • 如果字符串在 .NET 中是不可变的,那么为什么 Substring 需要 O(n) 时间?

    鉴于字符串在 NET 中是不可变的 我想知道为什么它们被设计成这样string Substring 需要 O substring Length 时间 而不是O 1 即 有什么权衡 如果有的话 更新 我非常喜欢这个问题 我刚刚在博客上写了它
  • 获取WPF路径的长度

    我用画了一条线PathGeometry 参考来自获取几何长度我使用 GetFlattenedPathGeometry 方法获取路径的长度 该方法会将路径转换为一系列直线 并将直线长度相加 参考的代码是 public static doubl
  • 如何在matplotlib中制作两个滑块

    我想在 matplotlib 中制作两个滑块来手动更改捕食者 猎物模型中的 N 和 P 值 import numpy as np import matplotlib pyplot as plt from scipy integrate im