使用 seaborn 绘制多个直方图

Posted

技术标签:

【中文标题】使用 seaborn 绘制多个直方图【英文标题】:Plot multiple histograms with seaborn 【发布时间】:2019-04-09 19:43:57 【问题描述】:

我有一个包含 36 列的数据框。我想使用 seaborn 一次性(6x6)为每个特征绘制直方图。基本上复制df.hist(),但使用seaborn。我下面的代码仅显示了第一个功能的图,其他所有功能都为空。

测试数据框:

df = pd.DataFrame(np.random.randint(0,100,size=(100, 36)), columns=range(0,36))

我的代码:

import seaborn as sns
# plot
f, axes = plt.subplots(6, 6, figsize=(20, 20), sharex=True)
for feature in df.columns:
    sns.distplot(df[feature] , color="skyblue", ax=axes[0, 0])

【问题讨论】:

ax=axes[0, 0] 表示您始终绘制到第一个轴。这也是你观察到的。也许您想绘制到不同的轴? 哦,原来如此。我应该如何改变它? 【参考方案1】:

我想同时循环遍历轴和特征是有意义的。

f, axes = plt.subplots(6, 6, figsize=(20, 20), sharex=True)
for ax, feature in zip(axes.flat, df.columns):
    sns.distplot(df[feature] , color="skyblue", ax=ax)

Numpy 数组是按行展平的,即您将在第一行获得前 6 个特征,在第二行获得第 6 到 11 个特征,依此类推。

如果这不是你想要的,你可以手动定义轴数组的索引,

f, axes = plt.subplots(6, 6, figsize=(20, 20), sharex=True)
    for i, feature in enumerate(df.columns):
        sns.distplot(df[feature] , color="skyblue", ax=axes[i%6, i//6])

例如以上将逐列填充子图。

【讨论】:

以上是关于使用 seaborn 绘制多个直方图的主要内容,如果未能解决你的问题,请参考以下文章

使用 Seaborn Python 绘制 CDF + 累积直方图

Python Seaborn 绘制空白直方图

使用 seaborn 为数据框绘制直方图

在 seaborn displot/histplot 函数中绘制高斯拟合直方图(不是 distplot)

如何绘制从不同列着色的堆叠 seaborn 直方图

seaborn可视化displot绘制直方图(histogram)并通过axvline函数在直方图中添加均值(mean)竖线(自定义均值竖线色彩)