1

I have pivoted a dataframe with 3 columns: Month, Clients and Quantity. I'm trying to bar plot this dataframe grouping by month and client, respectively, in order to know how much they've traded over the months.

could someone please help me? I've tried many ways but couldn't get even closer...

Expected Plot: Expected Plot

Original Dataframe (first 10 rows only)

Mes,Clientes,Mercadorias,Quantidade
Janeiro,Cliente A,DOL,834984
Janeiro,Cliente A,WDO,622107
Janeiro,Cliente A,IND,576051
Janeiro,Cliente A,WIN,326315
Janeiro,Cliente A,DI1,762236
Janeiro,Cliente B,DOL,696233
Janeiro,Cliente B,WDO,635564
Janeiro,Cliente B,IND,265720
Janeiro,Cliente B,WIN,550040
Janeiro,Cliente B,DI1,354343

Code used to pivot the dataframe:

df_2 = pd.pivot_table(df, index='Mes', columns='Clientes', aggfunc=sum)

Pivot Dataframe:

Quantidade,Quantidade,Quantidade,Quantidade,Quantidade
Cliente A,Cliente B,Cliente C,Cliente D,Cliente E
1799492,1779077,3278442,2307922,3037275
2434961,2153050,2433302,2537541,1991130
3121693,2501900,1902067,2899094,2395038
2526271,2922299,2719685,3352454,2756570
2918910,3806007,2114714,2302343,2077582
Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158

3 Answers3

1

It looks like you used df.pivot(), so you can basically do df.plot(kind='bar')

Hugolmn
  • 1,530
  • 1
  • 7
  • 20
1

You need to slice your dataframe so you eliminate that top level of your MultiIndex column header, use:

df_2['Quantidade'].plot.bar()

Output:

enter image description here

Another option is to use the values parameter in pivot_table, to eliminate the creation of the MultiIndex column header:

df_2 = pd.pivot_table(df, index='Mes', columns='Clientes', values='Quantidade', aggfunc=sum)

Output:

Clientes  Cliente A  Cliente B
Mes                           
Janeiro     3121693    2501900
Scott Boston
  • 147,308
  • 15
  • 139
  • 187
0

This will be a 2 step process.

  1. Unstack your dataframe - follow this example - Reshape wide to long in pandas

  2. Draw the grouped bar plot using matplotlib - follow this example - https://chrisalbon.com/python/data_visualization/matplotlib_grouped_bar_plot/

There is an easy method in Seaborn plotting library example - You can mention the second column as hue and this should do the work for you.

krksam19
  • 13
  • 3