使用分组依据绘制条形图

时间:2020-05-20 04:16:54

标签: python pandas plot

我使用

制作了一个数据框
 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

我需要获取条形图,

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轴->>值

您能建议我如何实现这一目标吗?

1 个答案:

答案 0 :(得分:1)

当您从DataFrame绘制 bar 图时,一般规则 标签的含义是:

  • x 标签是每一行的名称,
  • 传奇标签来自每一列,
  • y 标签是数字标签,允许读取每个条形的高度。

如您所愿,您想要 aa bb cc ,...(即名称) ) 作为x标签,条形图应通过换位生成 您的DataFrame。

一种生成它的方法是:

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

请注意结尾的;会阻止有关以下内容的打印输出: 创建的图片对象(类似 <matplotlib.axes._subplots.AxesSubplot at ...>

我添加了 rot = 0 参数,使x标签没有旋转,因为 默认旋转角度为90度。

为您的数据,略有变化以使高度没有太大不同 的酒吧,我得到了:

enter image description here

(我将 5500.0 更改为 855 ,否则一格会很高 以及其他所有非常低的内容。)