子图问题:如何通过分类值为每个图绘制直方图?

时间:2019-02-05 19:22:37

标签: python matplotlib histogram

我有一个带有三个数值变量孔隙度,烫发和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.

I would like to have this result,但x和y轴都带有标签名称。此外,为每个子图都有一个标题将很有帮助。

2 个答案:

答案 0 :(得分:0)

我只是用轮廓绘制了一个子图,但是我认为框架将非常相似:

fig, axs = plt.subplots(2, 2, constrained_layout=True)
for ax, extend in zip(axs.ravel(), extends):
    cs = ax.contourf(X, Y, Z, levels, cmap=cmap, extend=extend, origin=origin)
    fig.colorbar(cs, ax=ax, shrink=0.9)
    ax.set_title("extend = %s" % extend)
    ax.locator_params(nbins=4)
plt.show()

我认为要注意的重点(我从下面的链接中学到了这一点)是他们在for循环中使用zip(axs.ravel())来建立每个ax,然后在{ {1}}。我敢肯定,您可以根据自己的用途进行调整。

完整的示例可在以下网址获得:https://matplotlib.org/gallery/images_contours_and_fields/contourf_demo.html#sphx-glr-gallery-images-contours-and-fields-contourf-demo-py

答案 1 :(得分:0)

我找到了答案:

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()