Home > OS >  How to groupby aggregate min / max and plot grouped bars
How to groupby aggregate min / max and plot grouped bars

Time:12-01

I am trying to graph the functions of min () and max () in the same graph, I already could with the function of max () but how can I join the two in the same graph and that it can be displayed correctly? Example of my code and my output:

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

enter image description here

And my output of my dataframe:

               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]

CodePudding user response:

Step 1

Create a subplot to plot the data to

fig, ax = plt.subplots()

Step 2

Plot your DataFrame maximum and minimum to the specific axis

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')

You may need to adjust the zorder to get the effect of a stacked bar plot.

CodePudding user response:

  • The correct way is to aggregate multiple metrics at the same time with enter image description here

    • Use stacked=True for stacked bars
    ax = dfg.plot(kind='bar', figsize=(8, 6), title='Bill Length (mm)', xlabel='Species', ylabel='Length (mm)', rot=0, stacked=True)
    

    enter image description here

  • Related