简体   繁体   中英

Plot bar graph using group by

I made an dataframe using

 output=  {(0, 0): 50.0, (0, 1): 100.0, (0, 2): 100.0, (0, 3): 100.0, 
    (1, 0): 0, (1, 1): 0, (1, 2): 200.0, (1, 3): 75.0, 
    (2, 0): 0, (2, 1): 150.0, (2, 2): 150.0, (2, 3): 0, 
    (3, 0): 500.0, (3, 1): 500.0, (3, 2): 500.0, (3, 3): 500.0, 
    (4, 0): 0, (4, 1): 0, (4, 2): 5550.0, (4, 3):0 }

value=[aa,bb,cc,dd]
name=[a,b,c,d,e]

s=pd.Series(output).unstack()
s.columns = value
s.index = name
pd.set_option("display.width", 170)
print(s)

    aa        bb     cc     dd
a   50.0    100.0   100.0   100.0
b   0         0     200.0   75.0
c   0       150.0   150.0    0
d   500.0   500.0   500.0   500.0
e   0         0     5500.0   0

I need to get a bar graph,

x-Axis->>All labels of
aa (With in this group by a,b,c,d,e),bb(With in this group by a,b,c,d,e),cc(With in this group by a,b,c,d,e),dd(With in this group by a,b,c,d,e),ee(With in this group by a,b,c,d,e)

y-Axis->>Values

Could you advise how I can achieve this

When you draw a bar plot from a DataFrame, then the general rule of labelling is that:

  • x labels are names of each row,
  • legend labels are from each column,
  • y labels are numeric, allowing to read the height of each bar.

As you wrote that you want aa , bb , cc , ... (ie column names) as x labels, the bar plot should be generated from a transposition of your DataFrame.

One way to generate it is:

s.T.plot.bar(rot=0);

Note the terminating ; to block a printout concerning details of the created picture object (something like <matplotlib.axes._subplots.AxesSubplot at...> ).

I added rot=0 parameter to have x labels without rotation, as the default rotation is 90 (degrees).

For your data, slightly changed to get not very much different heights of bars, I got:

在此处输入图像描述

(I changed 5500.0 to 855 , otherwise one bar would be very high and all other very low.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM