现在我正在使用euler方法解决问题。我做了如下,但即使我移动slidr图表不会改变
from math import exp
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider, Button, RadioButtons
for i in range(1,n):
Nlist.append(Nlist[i-1]+dNlist[i-1]*deltat)
Qlist.append(Qlist[i-1]+Qlist[i-1]*deltat)
dNlist.append(Qlist[i]/(1+Qlist[i])*(1-Nlist[i]/Nmax)*Nlist[i])
tlist.append(t0+i*deltat)
x=tlist
y=Nlist
fig=plt.figure()
l=fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
l.plot(x,y,linewidth=2,color="red")
plt.xlabel("Value of t")
plt.ylabel("Value of N")
plt.title("Euler Method")
axcolor = 'lightgoldenrodyellow'
axQ0 = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
axNmax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axN0 = fig.add_axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
sQ0 = Slider(axQ0, 'init_Temp', 0, 0.1, valinit=Q0)
sNmax = Slider(axNmax, 'N_max', 1000, 100000, valinit=Nmax)
sN0 = Slider(axN0, "init_N",1,10,valinit=N0)
有关如何在Slider
上使用Matplotlib page的示例。
在该示例中,可以看到update
函数通过set_ydata()
将新创建或更改的数据设置为表示绘图线的matplotlib.lines.Line2D
对象。
在这里的代码中,您尝试将数据设置为matplotlib.axes._subplots.AxesSubplot
对象,这当然不起作用。它实际上应该抛出错误,'AxesSubplot' object has no attribute 'set_ydata'
。
因此,正确的代码应绘制到axes
对象并保存生成的Line2D
供以后使用。
ax=fig.add_subplot(111)
l, = ax.plot(x,y,linewidth=2,color="red")
为了完整起见,这里是完整的工作代码:
from __future__ import division
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider
t0=0
Q0=0.001
tf=25
N0=5
Nmax=10000
dN0=Q0/(1+Q0)*(1-N0/Nmax)*N0
n=100
deltat=(tf-t0)/(n-1)
tlist=[t0]
Nlist=[N0]
Qlist=[Q0]
dNlist=[dN0]
for i in range(1,n):
Nlist.append(Nlist[i-1]+dNlist[i-1]*deltat)
Qlist.append(Qlist[i-1]+Qlist[i-1]*deltat)
dNlist.append(Qlist[i]/(1+Qlist[i])*(1-Nlist[i]/Nmax)*Nlist[i])
tlist.append(t0+i*deltat)
x=tlist
y=Nlist
fig=plt.figure()
#########
### Changes here:
ax=fig.add_subplot(111)
fig.subplots_adjust(left=0.25, bottom=0.25)
l, = ax.plot(x,y,linewidth=2,color="red")
###########
plt.xlabel("Value of t")
plt.ylabel("Value of N")
plt.title("Euler Method")
axcolor = 'lightgoldenrodyellow'
axQ0 = fig.add_axes([0.25, 0.15, 0.65, 0.03], axisbg=axcolor)
axNmax = fig.add_axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
axN0 = fig.add_axes([0.25, 0.05, 0.65, 0.03], axisbg=axcolor)
sQ0 = Slider(axQ0, 'init_Temp', 0, 0.1, valinit=Q0)
sNmax = Slider(axNmax, 'N_max', 1000, 100000, valinit=Nmax)
sN0 = Slider(axN0, "init_N",1,10,valinit=N0)
def update(val):
ini_Q = sQ0.val
ini_Nmax = sNmax.val
ini_N =sN0.val
ini_dN=ini_Q/(1+ini_Q)*(1-ini_N/ini_Nmax)*ini_N
tlist2=[t0]
Nlist2=[ini_N]
Qlist2=[ini_Q]
dNlist2=[ini_dN]
for i in range(1,n):
Nlist2.append(Nlist2[i-1]+dNlist2[i-1]*deltat)
Qlist2.append(Qlist2[i-1]+Qlist2[i-1]*deltat)
dNlist2.append(Qlist2[i]/(1+Qlist2[i])*(1-Nlist2[i]/ini_Nmax)*Nlist2[i])
tlist2.append(t0+i*deltat)
l.set_ydata(Nlist2)
fig.canvas.draw_idle()
sQ0.on_changed(update)
sNmax.on_changed(update)
sN0.on_changed(update)
plt.show()