首页 > 解决方案 > 子图问题:如何通过分类值为每个图绘制直方图?

问题描述

我有一个包含三个数值变量 Porosity、Perm 和 AI 的 DataFrame。我想制作一个子图,在每个图中,我想要三个变量的直方图,通过分类变量“Facies”。相只能取两个值:Sand 和 Shale。

总之,每个子图都需要一个直方图,并且每个直方图都必须基于分类变量 Facies 进行绘制,以进行相间的比较。

到目前为止,我可以让它工作,但我不能将轴标题添加到每个子图。

plt.subplot(311)
plt.hist(df_sd['Porosity'].values, label='Sand', bins=30, alpha=0.6)
plt.hist(df_sh['Porosity'].values, label='Shale', bins=30, alpha=0.6)
ax.set(xlabel='Porosity (fraction)', ylabel='Density', title='Porosity              
      Histogram')
plt.legend()

plt.subplot(312)
plt.hist(df_sd['log10Perm'].values, label='Sand', bins=30, alpha=0.6,)
plt.hist(df_sh['log10Perm'].values, label='Shale', bins=30, alpha=0.6)
ax.set(xlabel='Permeability (mD)', ylabel='Density', title='Permeability 
Histogram')
plt.legend()

plt.subplot(313)
plt.hist(df_sd['AI'].values, label='Sand', bins=30, alpha=0.6)
plt.hist(df_sh['AI'].values, label='Shale', bins=30, alpha=0.6)
ax.set(xlabel='AI (units)', ylabel='Density', title='Acoustic Impedance 
Histogram')

plt.legend()
plt.subplots_adjust(left=0.0, bottom=0.0, right=1.5, top=3.5, wspace=0.1, 
hspace=0.2);


#I have tried with:
fig, axs = plt.subplots(2, 1)
but when I code
axs[0].hist(df_sd['Porosity'].values, label='Sand', bins=30, alpha=0.6)
axs[0].hist(df_sd['Porosity'].values, label='Shale', bins=30, alpha=0.6)

#But the histogram for shale overrides the histogram for Sand.

我想得到这个结果,但 x 和 y 轴都带有标签名称。此外,为每个子图设置一个标题会很有帮助。

标签: pythonmatplotlibhistogram

解决方案


我找到了答案:

fig = plt.figure()
ax = fig.add_subplot(111)
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax2 = fig.add_subplot(313)


plt.subplot(311)
ax1.hist(df_sd['Porosity'].values, label='Sand', bins=30, alpha=0.6)
ax1.hist(df_sh['Porosity'].values, label='Shale', bins=30, alpha=0.6)
ax1.set(xlabel='Porosity (fraction)', ylabel='Density', title='Porosity Histogram')
ax1.legend()

推荐阅读