我使用“plt.subplot(2,2,sharex=True,sharey=True)”来绘制一个2*2的子图。每个子批次有两个Y轴,并包含直方图上的正态分布曲线。注意,我在这里特别设置了“sharex=True,sharey=True”,以使所有子地块共享相同的X轴和Y轴
运行我的代码后,除了第二、三和第四个子图之外,一切都很好,其中正态分布曲线与柱状图拟合得不是很好(请参见这里的图)
我用谷歌搜索了一下,但没能解决这个问题。但是,如果我在代码中设置了“sharex=True,sharey=False”,那么该图看起来是正确的,但是所有子地块都使用自己的Y轴,这不是我想要的。请看这里的数字
希望StackOverflow的专家能解决这个问题。非常感谢
下面是我的代码:
import matplotlib.pyplot as plt
from scipy.stats import norm
def align_yaxis(ax1, v1, ax2, v2):
#adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1
_, y1 = ax1.transData.transform((0, v1))
_, y2 = ax2.transData.transform((0, v2))
inv = ax2.transData.inverted()
_, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
miny, maxy = ax2.get_ylim()
ax2.set_ylim(miny+dy, maxy+dy)
def drawSingle(myax, mydf , title, offset):
num_bins = 200
xs = mydf["gap"]
x = np.linspace(-1,1,1000)
mu =np.mean(x)
sigma =np.std(xs)
n, bins, patche = myax.hist(xs, num_bins, alpha=0.8, facecolor='blue', density=False)
myax.set_ylabel('frequency',color="black",fontsize=12, weight = "bold")
myax.set_xlabel('X', fontsize=12, weight = "bold",horizontalalignment='center')
ax_twin = myax.twinx()
y_normcurve = norm.pdf(bins, mu, sigma)
ax_twin.plot(bins, y_normcurve, 'r--')
align_yaxis(myax,0,ax_twin,0)
peakpoint = norm.pdf(mu,loc=mu,scale=sigma)
plt.vlines(mu, 0, peakpoint, 'y', '--', label='example')
ax_twin.set_ylabel("probablility dense",color="black",fontsize=12, weight = "bold")
def drawSubplots(mydf1,mydf2,mydf3,mydf4, pos1,pos2,pos3,pos4, title, filename):
plt.rcParams['figure.figsize'] = (18,15 )
my_x_ticks = np.arange(-0.8, 0.8,0.1)
rows, cols = 2, 2
fig, ax = plt.subplots(2, 2, sharex=True, sharey=True)
drawSingle(ax[0][0], mydf1, "Subplot1", pos1)
drawSingle(ax[0][1], mydf2, "Subplot2", pos2)
drawSingle(ax[1][0], mydf3, "Subplot3", pos3)
drawSingle(ax[1][1], mydf4, "Subplot4", pos4)
plt.text(-1, -1, title, horizontalalignment='center', fontsize=18)
plt.show()
drawSubplots(df1, df2,df3,df4,3.2,3.1,2.7,2.85,"test9", "test9")
以下是一个尝试:
非常感谢约翰,你太棒了
基于您的代码,我刚刚在DrawSubplot函数中添加了几行代码,以便使95%的高斯曲线区域在每个子图的下限和上限之间着色。以下是我的尝试。看来ax_twin.fill_between在这里不正常工作。从图中可以看出,阴影区域超出了高斯曲线enter image description here。我想要的只是在高斯曲线下的下限和上限之间对区域进行着色。如果你不介意的话,请你检查一下我的错误好吗?多谢各位
相关问题 更多 >
编程相关推荐