从熊猫df有效分配条形图

时间:2018-06-28 23:28:18

标签: python pandas matplotlib bar-chart

我目前正在根据bar chart pandas手动创建一个df。有没有更有效的方法可以直接从df读取它?

import pandas as pd
import matplotlib.pyplot as plt

d = ({
    'A' : ['1','1','1','2','2','2','3','3','3','3'],     
    'B' : ['A','B','C','A','B','C','D','A','B','C'],
    'C' : ['John','Carl','Carl','John','Lily','John','Lily','John','Carl','Carl'],         
    })

df = pd.DataFrame(data=d)

fig,ax = plt.subplots(figsize = (3,3))

Ay = [3]
Ax = [1]

By = [2,1]
Bx = [7,12]

Cy = [1,2]
Cx = [3,8]

Dy = [1]
Dx = [14]

plt.bar(Ax,Ay, label = 'A')
plt.bar(Bx,By, label = 'B')
plt.bar(Cx,Cy, label = 'C')
plt.bar(Dx,Dy, label = 'D')

plt.legend(loc = 'upper right')
plt.show()

如果我手动添加xticks以显示该人,则预期输出为:

enter image description here

2 个答案:

答案 0 :(得分:0)

您在数据框和绘图中的数据不匹配,例如John具有匹配的行

>>> df[df.C == "John"]
   A  B     C
0  1  A  John
3  2  A  John
5  2  C  John
7  3  A  John
>>>    

将数据框设置为图中的数据。

>>> d = ({
...     "A" : [3,1,2,2,1,1],
...     "B" : ["A", "C", "B", "C", "B", "D",],
...     "C" : ["John", "John", "Carl", "Carl", "Lily", "Lily"]
... })
>>>
>>> df = pd.DataFrame(data=d)

使用pivot重塑列和图的形状。

>>> df.pivot(index="C", columns="B", values="A").plot(kind="bar")

答案 1 :(得分:0)

您可以使用pivot_table

df.assign(A=df.A.astype(int)).pivot_table(index="C", columns="B", values="A",aggfunc='count').rename_axis(None).rename_axis(None,1).plot(kind='bar')

enter image description here