如何在 pandas 中制作直方图网格,并在所有直方图中使用公共图形

How to make a grid of histograms in pandas with a common graph in all of them

有没有办法使用 pandas.DataFrame.hist() 函数创建直方图网格,其中每个图形都包含一个特定变量,以及所有图形中的一个公共变量?例如,在下面的 DataFrame 中,我希望绘制深度,其中一个是长度,另一个是宽度。

import pandas as pd

df = pd.DataFrame({
     'length': [1.5, 0.5, 1.2, 0.9, 3, 0.4, 0.2],
     'width': [0.7, 0.2, 0.15, 0.2, 1.1, 0.2, 0.1],
     'depth': [1, 0.4, 0.5, 1.1, 2, 0.1, 0.9]
     }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse', 'cow', 'dog'])
hist = df.hist(bins=3)

我认为你需要重新绘制直方图:

# draw the histograms for other columns except `depth`
axes = df.drop('depth',axis=1).hist(bins=3)

# draw histogram for `depth` in each of the subplots
for ax in axes.flat:
    df['depth'].hist(bins=3, ax=ax, alpha=0.7)

输出: