【发布时间】:2020-09-25 20:11:37
【问题描述】:
我想绘制多个包含直方图的子图。此外,我想绘制一条曲线,显示每个子图的正态分布。虽然我在这个论坛上找到了关于如何在单个图(直方图)上绘制正态曲线的不同答案,但我正在努力用子图实现相同的效果。我尝试了以下方法:
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,但是我不知道如何将这两个命令单独放入子图中。有人对这个有经验么?我一直在尝试整个下午
任何帮助都非常感谢,在此先感谢!
【问题讨论】:
-
使用
ax1.get_xticks()和ax2.get_xticks()代替plt.xticks()。也许ax1.get_xlim(),因为它会直接获得限制,默认以正确的顺序。ax1.margins(x=0)会将新的限制再次设置为曲线的限制,因此它不会“悬空”。 This tutorial 可能会有所帮助。
标签: python matplotlib histogram