Matplotlib如何将概率密度函数叠加到基线图上

1qczuiv0  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(167)

我想在基线图上叠加一个概率分布。下面是一个MRE,然后通过在PowerPoint中复制/旋转/挤压图来显示所需的结果。

# Import python libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

# Plot example PDF
x1 = np.logspace(start=np.log(0.1), stop=np.log(3), num=200, base=np.e)
ln_mu, ln_sigma = 1.1, 0.3
y1 = np.exp(stats.norm.pdf(x1, ln_mu, ln_sigma))
fig, ax = plt.subplots()
ax.fill_between(x1, min(y1), y1, alpha=0.5)
ax.set(xscale="log", xlim=[min(x1), max(x1)])
plt.show()

# Plot example baseline curve
x2 = np.arange(0, 1.05, 0.05)
y2 = 2*np.sqrt(np.pi*x2)
fig, ax = plt.subplots()
ax.plot(x2,y2)
ax.set(yscale="log", ylim=[min(x1), max(x1)])
plt.show()

下面是我尝试使用matplotlib生成的结果。(PDF上的轴应该关闭,我只是为了说明这个例子而没有裁剪它们。)让我们假设PDF的右(直)边应该在x=0.1125处。

jw5wzhpr

jw5wzhpr1#

您需要twiny并使用fill_betweenx绘制分布:

# Import python libraries
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

# Plot example PDF
x1 = np.logspace(start=np.log(0.1), stop=np.log(3), num=200, base=np.e)
ln_mu, ln_sigma = 1.1, 0.3
y1 = np.exp(stats.norm.pdf(x1, ln_mu, ln_sigma))
fig, ax = plt.subplots()

x2 = np.arange(0, 1.05, 0.05)
y2 = 2*np.sqrt(np.pi*x2)
ax.plot(x2,y2)
ax.set(yscale="log", ylim=[min(x1), max(x1)])

ax2 = ax.twiny()
ax2.fill_betweenx(x1, min(y1), y1, alpha=0.5)
ax2.set(yscale="log", ylim=[min(x1), max(x1)])
plt.show()

相关问题