【问题标题】:How to groupby aggregate min / max and plot grouped bars如何分组聚合最小值/最大值并绘制分组条形图
【发布时间】:2022-01-07 15:37:42
【问题描述】:

我正在尝试将min ()max () 的函数绘制在同一个图中,我已经可以使用max () 的函数但是我如何将两者加入同一个图中并且可以显示正确吗? 我的代码和输出示例:

df.groupby('fecha_inicio')['capacidad_base_firme'].max().plot(kind='bar', legend = 'Reverse')
plt.xlabel('Tarifa de Base firme por Zona')

我的数据框输出:

               zona  capacidad_base_firme  ...  fecha_inicio   fecha_fin
0               Sur               1.52306  ...    2016-01-01  2016-03-31
1            Centro               2.84902  ...    2016-01-01  2016-03-31
2         Occidente               1.57302  ...    2016-01-01  2016-03-31
3             Golfo               3.06847  ...    2016-01-01  2016-03-31
4             Norte               4.34706  ...    2016-01-01  2016-03-31
..              ...                   ...  ...           ...         ...
67            Golfo               5.22776  ...    2017-10-01  2017-12-31
68            Norte               6.99284  ...    2017-10-01  2017-12-31
69            Istmo               7.25957  ...    2017-10-01  2017-12-31
70         Nacional               0.21971  ...    2017-10-01  2017-12-31
71  Nacional con AB              -0.72323  ...    2017-10-01  2017-12-31

[72 rows x 10 columns]

【问题讨论】:

    标签: python pandas matplotlib group-by bar-chart


    【解决方案1】:
    • 正确的做法是用.agg同时聚合多个metrics,然后直接用pandas.DataFrame.plot绘图
      • 无需为每个指标调用.groupby。对于非常大的数据集,这可能会占用大量资源。
      • 也无需单独调用matplotlib 来创建图形和坐标轴,因为这是由pandas.DataFrame.plot 处理的,它使用matplotlib 作为默认后端。
    • python 3.9.7pandas 1.3.4matplotlib 3.5.0中测试
    import seaborn as sns  # for data
    import pandas as pd
    import matplotlib.pyplot as plt
    
    # load the test data
    df = sns.load_dataset('penguins')
    
    # display(df.head(3))
      species     island  bill_length_mm  bill_depth_mm  flipper_length_mm  body_mass_g     sex
    0  Adelie  Torgersen            39.1           18.7              181.0       3750.0    Male
    1  Adelie  Torgersen            39.5           17.4              186.0       3800.0  Female
    2  Adelie  Torgersen            40.3           18.0              195.0       3250.0  Female
    
    # aggregate metrics on a column
    dfg = df.groupby('species').bill_length_mm.agg(['min', 'max'])
    
    # display(dfg)
                min   max
    species              
    Adelie     32.1  46.0
    Chinstrap  40.9  58.0
    Gentoo     40.9  59.6
    
    # plot the grouped bar
    ax = dfg.plot(kind='bar', figsize=(8, 6), title='Bill Length (mm)', xlabel='Species', ylabel='Length (mm)', rot=0)
    plt.show()
    

    • stacked=True 用于堆叠条形
    ax = dfg.plot(kind='bar', figsize=(8, 6), title='Bill Length (mm)', xlabel='Species', ylabel='Length (mm)', rot=0, stacked=True)
    

    【讨论】:

    • 非常感谢您的回答,这对我学习 Python 有很大帮助!
    【解决方案2】:

    第 1 步

    创建一个子图来绘制数据

    fig, ax = plt.subplots()
    

    第 2 步

    将 DataFrame 最大值和最小值绘制到特定轴

    df.groupby('fecha_inicio')['capacidad_base_firme'].max().plot(ax = ax, kind='bar', legend = 'Reverse', label='Maximum')
    df.groupby('fecha_inicio')['capacidad_base_firme'].min().plot(ax = ax, kind='bar', legend = 'Reverse', label='Minimum')
    

    您可能需要调整 zorder 以获得堆积条形图的效果。

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多