在Python中打开循环内部的Plots



我在使用matplotlib时遇到了一个非常奇怪的问题。我有一个遍历模型不同情况的循环,对于每个情况,我希望它将求解的微分方程输出为图形,然后询问用户是否愿意继续绘图。以下是我目前正在使用的代码(为了简单起见,只有一种情况(:

import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
P1 = 100
P2 = 20
Pa = 14.6959
L = 11.811
D = 7/16
Ac= math.pi/4*D**2 
Ar = .0305 
ML = 2.2
MP = .31
v = .1
C = .95
k = 1

#Defines the Function to Solve the ODE
def dU_dx(U, x):
return [U[1],(P1*Ac-P2*Ac-Pa*Ar-(1-C)*v*U[1]-k*U[0])/(ML+MP)]
i =0
U0 = [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 ODE
while 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) ")

if answer == "y":
case = int(input("Enter the new case number : "))
elif answer == "n":
i = 2      
else:
print("Please enter y or 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.plot下面添加plt.show(block=True)来显示绘图,但是在这样做之后,代码在显示图形后仍然会停止,并且不允许代码继续。

这个循环的最终目标是绘制一个ODE的解决方案,然后询问用户是否希望绘制另一个具有略微不同常量的相同形式的ODE。我如何让Python允许我在这个循环中绘制函数,并允许切换用例?

非常感谢你的帮助!

我认为您可能正在使用IDE运行;block=false";参数在使用我的mac终端启动时运行良好,并且按照您的意愿运行。IDE通常不允许这样做。您的代码完全正确。

最新更新