Pandas将数据帧特定列计数绘制为条形

时间:2017-05-02 22:49:49

标签: python pandas matplotlib

如果我有一个数据框如下

column1                column2
key1Str         valueAsString1
key2Str         valueasString2
key2Str         valueasString1
key1Str         valueasString2
key3Str         valueasString1
key1Str         valueasString2

我想将其绘制为条形图,其中x轴是每个键,每个值和y应该是数据帧中每个值的计数。我对python很新,并尝试按如下方式执行。

将摘要编号为(key1 - value1Count,value2Count,key2- value1Count,value2Count ....)

fig, ax = plt.subplots()
for key in df['column1'].unique():
    data_=df[df['column1']==key]
    data_['column2'].values_count().plot(kind='bar', ax=ax)
plt.show()

最后只显示一张图表,有什么更好的方法呢?

1 个答案:

答案 0 :(得分:3)

IIUC:

import seaborn as sns

sns.barplot(x='column1', y='cnt', hue='column2',
            data=df.groupby(df.columns.tolist()).size().to_frame('cnt').reset_index())

enter image description here