【问题标题】:Matplotlib boxplot with one box for each category or value in a columnMatplotlib 箱线图,每列中的每个类别或值都有一个框
【发布时间】:2020-03-02 05:19:11
【问题描述】:

我有一个这样的csv(分隔符是;

Day;col_1;col_2;col_3;month
20180101;652;0;25803;1
20180102;737;6;25677;1
20180103;653;10;27955;1
20180104;914;10;27722;1
[a lot of rows]
20181228;924;35;30191;12
20181229;721;18;28601;12
20181230;902;17;28098;12
20181231;778;30;28909;12

我想在单独的轴上绘制 col_1col_2col_3 列的值。 在每个轴上,我希望每个月都有一个不同的框

我知道这是在 seaborn 中仅针对一列执行此操作的方法,但我想仅使用 pandasmatplotlib 来执行此操作:

import seaborn as sns
sns.boxplot(data=df, x='month', y='col1')

this post查看后,我发现这可能与我想要的非常接近:

df.assign(index=df.groupby('month').cumcount()).pivot('index','month','col1').plot(kind='box')

有没有更有效的方法?

如何在同一个图中为每个colX 添加几个轴(意思是子图)?

【问题讨论】:

  • df.assign(...).pivot(...).plot.box(subplots=True)?
  • @QuangHoang 它不起作用

标签: python pandas matplotlib boxplot


【解决方案1】:

考虑 matplotlib subplots 和每列的元素,对于每个数字 y 列,迭代地将轴传递到 seaborn 的 boxplotax

fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(12,4))

for i, col in enumerate(["col_1", "col_2", "col_3"]):
   sns.boxplot(data=df, x='month', y=col, ax=ax[i])
   ax[i].set_title(col.title())

plt.tight_layout()

plt.show()
plt.clf()
plt.close()

用随机数据演示

np.random.seed(1142019)

df = pd.DataFrame({'Day': pd.date_range('2018-01-01', '2018-12-31'),
                   'col_1': np.random.randint(1, 10, 365),
                   'col_2': np.random.randint(10, 100, 365),
                   'col_3': np.random.randint(2500, 29999, 365)
                  })

df['month'] = df['Day'].dt.month

以上代码,生成此图

【讨论】:

    猜你喜欢
    • 2018-07-20
    • 2021-09-07
    • 1970-01-01
    • 2016-10-30
    • 2021-07-31
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多