在子图直方图上绘制范数曲线

plot norm curve over subplotted histograms

我想绘制多个包含直方图的子图。此外,我想绘制一条曲线,显示每个子图的正态分布。虽然我在这个论坛上找到了关于如何在单个图(直方图)上绘制正态曲线的不同答案,但我正在努力通过子图实现相同的效果。我尝试了以下方法:

from scipy import stats  
import numpy as np  
import matplotlib.pylab as plt

fig, ((ax1, ax2)) = plt.subplots(1,2,figsize=(10,4))

# create some normal random noisy data
data1 = 50*np.random.rand() * np.random.normal(10, 10, 100) + 20
data2=  50*np.random.rand() * np.random.normal(10, 10, 100) + 50

# plot normed histogram
ax1.hist(data1, density=True)

# find minimum and maximum of xticks,
xt = plt.xticks()[0]  
xmin, xmax = min(xt), max(xt)  
lnspc = np.linspace(xmin, xmax, len(data1))

# lets try the normal distribution first
m1, s1 = stats.norm.fit(data1) # get mean and standard deviation  
pdf_1 = stats.norm.pdf(lnspc, m1, s1) # now get theoretical values in our interval  
ax1.plot(lnspc, pdf_1, label="Norm") # plot it

# plot second hist
ax2.hist(data2, density=True)

# find minimum and maximum of xticks
xt = plt.xticks()[0]  
xmin, xmax = min(xt), max(xt)  
lnspc = np.linspace(xmin, xmax, len(data2))

# lets try the normal distribution first
m2, s2 = stats.norm.fit(data2) # get mean and standard deviation  
pdf_2 = stats.norm.pdf(lnspc, m2, s2) # now get theoretical values in our interval  
ax2.plot(lnspc, pdf_2, label="Norm") # plot it
plt.show()  

现在我的问题是正态曲线对于第二个图总是最优的,但不是第一个。这是因为 xmin 和 xmax,但是我不知道如何将这两个命令分别放入子图中。有人对这个有经验么?我整个下午都在努力

非常感谢任何帮助,提前致谢!

您可以使用 axes 代替元组。然后您可以使用 sca 单独设置每个轴。如果这就是您所需要的,请参阅下文。

from scipy import stats  
import numpy as np  
import matplotlib.pylab as plt


# fig, ((ax1, ax2)) = plt.subplots(1,2,figsize=(10,4)) << INSTEAD OF THIS DO:
fig, axes = plt.subplots(nrows = 1, ncols = 2,figsize=(10,4))

# create some normal random noisy data
data1 = 50*np.random.rand() * np.random.normal(10, 10, 100) + 20
data2=  50*np.random.rand() * np.random.normal(10, 10, 100) + 50


plt.sca(axes[0]) #Refer to the first axis
# plot normed histogram
axes[0].hist(data1, density=True)

# find minimum and maximum of xticks,
xt = plt.xticks()[0]  
xmin, xmax = min(xt), max(xt)  
lnspc = np.linspace(xmin, xmax, len(data1))

# lets try the normal distribution first
m1, s1 = stats.norm.fit(data1) # get mean and standard deviation  
pdf_1 = stats.norm.pdf(lnspc, m1, s1) # now get theoretical values in our interval  
axes[0].plot(lnspc, pdf_1, label="Norm") # plot it



plt.sca(axes[1]) #Refer to the second axis
# plot second hist
axes[1].hist(data2, density=True)

# find minimum and maximum of xticks
xt = plt.xticks()[0]  
xmin, xmax = min(xt), max(xt)  
lnspc = np.linspace(xmin, xmax, len(data2))

# lets try the normal distribution first
m2, s2 = stats.norm.fit(data2) # get mean and standard deviation  
pdf_2 = stats.norm.pdf(lnspc, m2, s2) # now get theoretical values in our interval  
axes[1].plot(lnspc, pdf_2, label="Norm") # plot it
plt.show()