pandas直方图:将每一列的直方图作为一个大图的子图进行绘制。

15

我正在使用以下代码,尝试将我的Pandas数据框df_in的每一列的直方图作为大图中的子图绘制出来。

%matplotlib notebook
from itertools import combinations
import matplotlib.pyplot as plt

fig, axes = plt.subplots(len(df_in.columns) // 3, 3, figsize=(12, 48))
for x in df_in.columns:
    df_in.hist(column = x, bins = 100)

fig.tight_layout()

然而,直方图没有显示在子图中。有人知道我错过了什么吗?谢谢!

1
据我所知,您需要在 df_in.hist(..., ax=your_ax) 中指定 ax 参数。 - MaxU - stand with Ukraine
顺带一提:此片段中导入 itertools 的 combinations 模块是没有使用到的。 - ABC
4个回答

14

我无法对burhan的答案进行评论,因为我的声望点数不够。他的答案存在问题,即axes不是一维的,它包含轴三元组,因此需要展开:

%matplotlib notebook
from itertools import combinations
import matplotlib.pyplot as plt

fig, axes = plt.subplots(len(df_in.columns)//3, 3, figsize=(12, 48))

i = 0
for triaxis in axes:
    for axis in triaxis:
        df_in.hist(column = df_in.columns[i], bins = 100, ax=axis)
        i = i+1

7
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

fig, axis = plt.subplots(2,3,figsize=(8, 8))
df_in.hist(ax=axis)

以上代码将绘制一个2*3(总共6个直方图)的数据框。根据您的排列要求(列数),调整行和列。

我的助教@Benjamin曾告诉我,数据框意味着不必使用for循环。


3
需要指定绘图的轴。以下方法应该有效:
fig, axes = plt.subplots(len(df_in.columns)//3, 3, figsize=(12, 48))
for col, axis in zip(df_in.columns, axes):
    df_in.hist(column = col, bins = 100, ax=axis)

我遇到了这个错误:ValueError: 传递的轴数必须为1,与输出图相同。我该如何修复这个轴问题?谢谢。 - Edamame
我没有注意生成坐标轴的那一行代码。可能存在问题,请根据您想要呈现图形的方式进行更改。例如,这将会将它们并排显示。“fig, axes = plt.subplots(1, len(df_in.columns))”。如果可以,请告诉我这是否有效。 - burhan
4
我喜欢这个答案比下面的Pascal更多,但是他提到有一个错误。对我来说,axes.flatten()解决了问题。 - Marcus V.

0

偶然发现了这篇古老的帖子,想着我应该添加一个正确的答案,上面的回答大部分是正确的,但忽略了需要对取整函数+1的事实。在@burhan的回答中有一定程度的解决,但我在这里做了一些调整:

import seaborn as sns
from matplotlib import pyplot as plt

def plot_univariate_distributions(df, numcols=3, fig_kwargs = dict()):
    fig, axes = plt.subplots(1+len(df.columns)//numcols, numcols, **fig_kwargs)
    for col, ax in zip(df.columns, axes.flat):
        sns.histplot(df[col], ax=ax)
        ax.set_title(col, size=10)
    plt.tight_layout()

plot_univariate_distributions(mydf, fig_kwargs={'figsize':[10,5]})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接