从熊猫数据框中制作多个饼图(每列一个)

时间:2020-06-24 11:45:09

标签: pandas pie-chart

我的问题类似于 Making multiple pie charts out of a pandas dataframe (one for each row).

但是,我要寻找的是每列而不是每一行。 我可以为每列制作饼图,但是,由于我有12列,所以饼图之间的距离太近了。

我使用了以下代码:

fig, axes = plt.subplots(4, 3, figsize=(10, 6))

for i, (idx, row) in enumerate(df.iterrows()):
    ax = axes[i // 3, i % 3]
    row = row[row.gt(row.sum() * .01)]
    ax.pie(row, labels=row.index, startangle=30)
    ax.set_title(idx)

fig.subplots_adjust(wspace=.2)

我得到以下结果

![enter image description here

但是我要在另一边。我需要有12个饼图(因为我有12列),每个饼图应有4个部分(分别是腿,车,步行和自行车)

如果我写这段代码

fig, axes = plt.subplots(4,3)
for i, col in enumerate(df.columns):
    ax = axes[i // 3, i % 3]
    plt.plot(df[col])

然后我得到以下结果: enter image description here

如果我使用的话:

plot = df.plot.pie(subplots=True, figsize=(17, 8),labels=['pt','car','walk','bike'])

然后我得到以下结果: enter image description here 这正是我想要的。但无法读取饼图。如果可以产生更清晰的输出,那就更好了。

2 个答案:

答案 0 :(得分:0)

在您的链接文章中,我将为此使用matplotlib.pyplot。可接受的答案使用plt.subplots(2, 3),我建议这样做以创建两行,每行中有3个图。 像这样:

fig, axes = plt.subplots(2,3)
for i, col in enumerate(df.columns):
    ax = axes[i // 3, i % 3]
    ax.plot(df[col])

答案 1 :(得分:0)

最后,我明白如果我交换行和列

df_sw = df.T

然后我可以在示例中使用代码: Making multiple pie charts out of a pandas dataframe (one for each row)