pandas 堆积的条形图 [英] Pandas stacked bar chart

查看:81
本文介绍了 pandas 堆积的条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据集:

SessionId    Query
   1           a   
   1           b
   2           a
   3           b
   3           b
   3           c
   3           a

我想显示一个堆叠的条形图,其中每个 Session 都有一个条形图,并且该条形图对于每个具有 Query 的条形图都由不同的颜色组成,堆叠大小将取决于每个会话中查询的数量.

I want to display a stacked bar chart where there will be a bar for each Session and the bar will consist of different colors for each Query that it has, the stacked size will be in the size of the number of queries in each session.

我尝试过这样的事情:

result = data.groupby('SessionId').apply(
   lambda group: (
      group.groupby('Query').apply(
         lambda queryGroup: (
            queryGroup.count()
         )                
      )
   )
 ) 

但是它在表格内提供了一个奇怪的表格

But it gives a weird table inside a table

推荐答案

crosstab should do the job if I understand your question correctly:

import pandas as pd

data = pd.DataFrame({'SessionId': [1, 1, 2, 3, 3, 3, 3], 
                     'Query': ['a', 'b', 'a', 'b', 'b', 'c', 'a']})

pd.crosstab(data.SessionId, data.Query).plot.barh(stacked=True)

这篇关于 pandas 堆积的条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆