我正在尝试绘制看起来好像呈指数下降的图形(见图),但我似乎无法让它工作......

import numpy as np
import matplotlib.pyplot as plt

p0 = 1013.
Rd = 0.2871
g = 0.00981
T = T0 = 288.
y = 0.000006
H = (Rd*T)/g
z = np.arange(0.,1600.,)
yz = y*z
yR = y*Rd

p1 = (p0)*(np.exp(-z/H))

p2 = (p0)*(((T-yz)/T)**(g/yR))


plt.plot(p1,z,'g-')
plt.plot(p2,z,'r--')

plt.legend(['Isothermal', 'Constant γ'])
plt.title('Pressure (mb) vs. Altitude (km) --  Brandi Slavich')
plt.xlabel("Pressure (mb)")
plt.ylabel('Altitude (km)')
plt.grid(linestyle='--')
plt.axis([100.,1000.,0.,16.])
plt.show()


TypeError: only length-1 arrays can be converted to Python scalars
---> p1 = (p0)*(exp(-z/H))

目标图:

最佳答案

错误来自 exp(-z/H) 。为避免这种情况,您可以改用 np.exp

看起来 math.exp 只能处理标量或形状为 (1, ) 的 numpy.ndarray

import numpy as np
import math

math.exp(np.array([100]))
# 2.6881171418161356e+43

math.exp(np.array([100, 200]))
# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# TypeError: only length-1 arrays can be converted to Python scalars

np.exp(np.array([100, 200]))
# array([  2.68811714e+43,   7.22597377e+86])

添加:

另外,我认为您的绘图 [100.,1000.,0.,16.] 的轴范围不适合您的数据范围( zp1p2 )。
# y-axis: 0 - 16
# >>> (z.min(), z.max())
# (0.0, 1599.0)

# x-axis: 100 - 1000
# >>> (p1.min(), p1.max())
# (837.95200017838602, 1013.0)
# >>> (p2.min(), p2.max())
# (835.24824032186791, 1013.0)

关于python - 给定一个图像,尽你所能创建与显示完全相同的图,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48778734/

10-12 22:24