如何使用vincent绘制pandas groupby结果

时间:2014-01-08 01:31:59

标签: python pandas

我使用以下语句使用multiplt键进行groupby

CountryBrowser = impressions.groupby(['Country', 'Browser']).size()

结果如下

 Country      Browser                           
 Afghanistan  Firefox 3.Any                          1
              Firefox Other.Other                    5
              Google Chrome                          5
              Safari (iPad) Any.Any                  1
              Safari 5.Any                           1
 Albania      Firefox Other.Other                    3
              Google Chrome                         15
              Microsoft Internet Explorer 10.Any     1
 Algeria      Firefox Other.Other                   31
              Google Chrome                         31
              Microsoft Internet Explorer 10.Any     1
              Opera 11.Any                           1
              Safari (iPad) Any.Any                  1

我想使用vincent或Matplotlib绘制它,我有以下代码,它对我不起作用

gbar = vincent.GroupedBar(CountryBrowser)
gbar.axis_titles(x='Country', y='Impressions')
gbar.legend(title='Browser')
gbar.display()

https://vincent.readthedocs.org/en/latest/quickstart.html#grouped-bar

1 个答案:

答案 0 :(得分:3)

对于分组栏,vincent需要1级索引,并使用组的列。您有MutliIndex个列。幸运的是,您可以通过简单的unstack()

来了解vincent所期望的内容
In [8]: idx = pd.MultiIndex.from_tuples([('a', 1), ('a', 2), ('b', 1), ('b', 2)])

In [9]: s = pd.Series(np.random.uniform(size=4), index=idx)

In [10]: s  # This is what you have
Out[10]: 
a  1    0.921138
   2    0.677708
b  1    0.916239
   2    0.130728
dtype: float64

In [11]: s.unstack()  # This is what you want
Out[11]: 
          1         2
a  0.921138  0.677708
b  0.916239  0.130728

[2 rows x 2 columns]

In [13]: group = vincent.GroupedBar(s.unstack())

In [14]: group.display()
<IPython.core.display.HTML at 0x103faa850>
<IPython.core.display.Javascript at 0x104957850>