使用 matplotlib 时我遇到了一个很奇怪的问题。我有一个循环遍历模型的不同情况,对于每种情况,我希望它以图形形式输出求解的微分方程,然后询问用户是否想继续绘制图形。这是我目前正在使用的代码(为简单起见,只有一个案例):import mathimport numpy as npimport matplotlib.pyplot as pltfrom scipy.integrate import odeintP1 = 100P2 = 20Pa = 14.6959L = 11.811D = 7/16Ac= math.pi/4*D**2 Ar = .0305 ML = 2.2MP = .31v = .1C = .95k = 1#Defines the Function to Solve the ODEdef dU_dx(U, x): return [U[1],(P1*Ac-P2*Ac-Pa*Ar-(1-C)*v*U[1]-k*U[0])/(ML+MP)]i =0U0 = [0, 0]t = np.linspace(0, 10, 200)case = input("What state is the loop in (1-4)?")case = int(case)#The While Loop to Iterate through states and output the graph of the ODEwhile i < 2: if case == 1: P1 = 100 P2 = 20 dU_dx Usol = odeint(dU_dx, U0, t) xsol = Usol[:,0] plt.plot(t,xsol); plt.show(block=False) answer = input("Continue to plot? (y/n) ") if answer == "y": case = int(input("Enter the new case number : ")) elif answer == "n": i = 2 else: print("Please enter y or n.") if case == 2: P1 = 100 P2 = 0 dU_dx Usol = odeint(dU_dx, U0, t) xsol = Usol[:,0] plt.plot(t,xsol); plt.show(block=False) answer = input("Continue to plot? (y/n) ") #The code for states 3 and 4 are identical to the code for states 1 and 2, with different values for P1 and P2. I haven't written them yet, and including them would only make the could longer with no additional insights. else: print ("Inproper state!") case = int(input("Specify a new case number : "))plot 函数的两个输入在循环外的函数中定义,并在循环外按预期工作。但是,当代码运行时,代码会跳过图形,然后不会提示用户输入并继续运行。我已经设法通过添加plt.show(block=True)below来显示图plt.plot,但是在这样做之后,代码仍然会在显示图形后停止并且不允许代码继续。此循环的最终目标是绘制 ODE 的解,然后询问用户是否愿意绘制另一个具有略微不同常数的相同形式的 ODE。我怎样才能让 Python 允许我在这个循环中绘制我的函数并允许切换案例?
1 回答
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
我认为您可能正在使用 IDE 运行,“block=false”参数在使用我的 mac 终端启动时工作正常,并且按照您的预期工作。IDE 通常不允许这样做。您的代码完全正确。
添加回答
举报
0/150
提交
取消