简体   繁体   English

熊猫堆积的条形图

[英]Pandas stacked bar chart

I have the following dataset: 我有以下数据集:

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

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. 我想显示一个堆积的条形图,其中每个会话将有一个条形,并且该条形将由它具有的每个查询包含不同的颜色,堆积的大小将是每个会话中查询数量的大小。

I tried something like this: 我尝试过这样的事情:

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: 如果我正确理解了您的问题,则crosstab应该可以完成此工作:

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 stacked bar chart relies on plotting different columns, so you'd need to pivot your data table to get the queries as columns holding the number of queries in rows. 熊猫堆积的条形图依赖于绘制不同的列,因此您需要旋转数据表以将查询作为包含行中查询数量的列来获取。

Try this: 尝试这个:

df = pd.DataFrame({"session":[1,1,2,2,3,3],
              "query":list("ababab"), "count":[5,7,32,5,8,1]})
df.pivot("session","query").plot(kind="bar", stacked=True)

Output: 输出:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM