2015-06-24 112 views
31

分类数据我有一个分类数据的数据帧:绘制与大熊猫和matplotlib

 colour direction 
1 red  up 
2 blue up 
3 green down 
4 red  left 
5 red  right 
6 yellow down 
7 blue down 

我想要生成一些图表,如基于类别饼图和柱状图。有没有可能创建虚拟数字变量?像

df.plot(kind='hist') 

回答

64

东西,你可以简单地在系列使用value_counts

df['colour'].value_counts().plot(kind='bar') 

enter image description here

+0

暗示'DF [ “颜色”。value_counts()。图(KIND = '酒吧')'共同替代 – openwonk

+0

是否可以指定x标签的顺序? –

13

这样的:

df.groupby('colour').size().plot(kind='bar') 
9

您可能会发现从statsmodels有用mosaic情节。这也可以为差异提供统计突出显示。

from statsmodels.graphics.mosaicplot import mosaic 
plt.rcParams['font.size'] = 16.0 
mosaic(df, ['direction', 'colour']); 

enter image description here

但0大小的蜂窝状的提防 - 它们会导致与标签的问题。

this answer的细节

+0

谢谢。我一直收到 ValueError:无法将NA转换为整数。 – Ivan

+1

这就是为什么我引用[这个答案](http://stackoverflow.com/a/31031988/4077912)。它应该有助于解决这个问题。 – Primer