gpt4 book ai didi

python - 更改函数中的变量以在同一轴上创建多个绘图

转载 作者:行者123 更新时间:2023-12-01 03:18:38 25 4
gpt4 key购买 nike

我目前正在尝试绘制一个函数,该函数描述不同世界模型的宇宙学中的线性扰动增长。我希望能够将所有曲线放在同一组轴上,但在设置方面遇到了困难。

我的目标是绘制该函数 D 相对于 z 的图,但有多个具有不同密度参数 ($\Omega$) 的图。

我已经管理了两个解决方案,但都不能完美工作,第一个非常低效(为每组参数添加新函数):

z = np.arange(0.0,10,0.1)

#density parameters
MOm = 1.0
MOv = 0.0

COm = 0.3
COv = 0.7

H0 = 70

def Mf(z):
A = (5/2)*MOm*(H0**2)
H = H0 * np.sqrt( MOm*((1+z)**3) + MOv )
return A * ((1+z)/(H**3))

def MF(z):
res = np.zeros_like(z)
for i,val in enumerate(z):
y,err = integrate.quad(Mf,val,np.inf)
res[i] = y
return res

def MD(z):
return (H0 * np.sqrt( MOm*((1+z)**3) + MOv )) * MF(z)

def Cf(z):
A = (5/2)*COm*(H0**2)
H = H0 * np.sqrt( COm*((1+z)**3) + COv )
return A * ((1+z)/(H**3))

def CF(z):
res = np.zeros_like(z)
for i,val in enumerate(z):
y,err = integrate.quad(Cf,val,np.inf)
res[i] = y
return res

def CD(z):
return (H0 * np.sqrt( COm*((1+z)**3) + COv )) * CF(z)


plt.plot(z,MD(z),label="Matter Dominated")
plt.plot(z,CD(z),label="Current Epoch")

因此,我尝试使用 for 循环使其变得更简单,但无法弄清楚如何向循环内的每个图添加标签:

Om = (1.0,0.3)
Ov = (0.0,0.7)

for param1,param2 in zip(Om,Ov):
def f(z):
A = (5/2)*param1*(H0**2)
H = H0 * np.sqrt( param1*((1+z)**3) + param2 )
return A * ((1+z)/(H**3))

def F(z):
res = np.zeros_like(z)
for i,val in enumerate(z):
y,err = integrate.quad(f,val,np.inf)
res[i] = y
return res

def D(z):
return (H0 * np.sqrt( param1*((1+z)**3) + param2 )) * F(z)

plt.plot(z,D(z))

有人可以帮忙解释一下有效的方法吗?或者如何使用 for 循环将标签动态添加到绘图中。任何帮助将不胜感激。

最佳答案

So I tried to make it simpler with a for loop, but have been unable to work out how to add labels to each plot inside the loop

from scipy import integrate
from matplotlib import pyplot as plt

MOm = 1.0
MOv = 0.0

COm = 0.3
COv = 0.7

z = np.arange(0.0,10,0.1)
H0 = 70
Om = (1.0,0.3)
Ov = (0.0,0.7)

fig = plt.figure(1)
for param1,param2 in zip(Om,Ov):
def f(z):
A = (5/2)*param1*(H0**2)
H = H0 * np.sqrt( param1*((1+z)**3) + param2 )
return A * ((1+z)/(H**3))

def F(z):
res = np.zeros_like(z)
for i,val in enumerate(z):
y,err = integrate.quad(f,val,np.inf)
res[i] = y
return res

def D(z):
return (H0 * np.sqrt( param1*((1+z)**3) + param2 )) * F(z)

## Now define labels as you need and labels as follows:

plt.plot(z,D(z),label = 'Om: {}, Ov: {}'.format(param1,param2))
plt.legend()

enter image description here

关于python - 更改函数中的变量以在同一轴上创建多个绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42212575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com