将Pandas crosstab与Seaborn堆叠式Barplots结合使用 [英] Using Pandas crosstab with seaborn stacked barplots

查看:351
本文介绍了将Pandas crosstab与Seaborn堆叠式Barplots结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用数据框在seaborn中创建一个堆积的条形图.

I am trying to create a stacked barplot in seaborn with my dataframe.

我首先像这样在熊猫中生成了一个交叉表:

I have first generated a crosstab table in pandas like so:

pd.crosstab(df['Period'], df['Mark'])

返回:

  Mark            False  True  
Period BASELINE    583    132
       WEEK 12     721      0 
       WEEK 24     589    132 
       WEEK 4      721      0

我想使用seaborn来创建一个叠合的条形图,以实现一致性,这就是我在其余图形中使用的方法.但是,由于无法索引交叉表,我一直在努力做到这一点.

I would like to use seaborn to create a stacked barplot for congruence, ans this is what I have used for the rest of my graphs. I have struggled to do this however as I am unable to index the crosstab.

我已经能够使用.plot.barh(stacked=True)在大熊猫上绘制我想要的情节,但没有Seaborn带来的运气.任何想法我该怎么做?

I have been able to make the plot I want in pandas using .plot.barh(stacked=True) but no luck with seaborn. Any ideas how i can do this?

谢谢

推荐答案

如您所说,您可以使用熊猫来创建堆叠的条形图.想要拥有季节性地块"的论点是无关紧要的,因为每个季节性地块和每个熊猫地块最终都只是matplotlib对象,因为两个库的绘图工具都只是matplotlib包装器.

As you said you can use pandas to create the stacked bar plot. The argument that you want to have a "seaborn plot" is irrelevant, since every seaborn plot and every pandas plot are in the end simply matplotlib objects, as the plotting tools of both libraries are merely matplotlib wrappers.

这是一个完整的解决方案(从@andrew_reece的答案中获取数据创建).

So here is a complete solution (taking the datacreation from @andrew_reece's answer).

import numpy as np 
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

n = 500
mark = np.random.choice([True,False], n)
periods = np.random.choice(['BASELINE','WEEK 12', 'WEEK 24', 'WEEK 4'], n)

df = pd.DataFrame({'mark':mark,'period':periods})
ct = pd.crosstab(df.period, df.mark)

ct.plot.bar(stacked=True)
plt.legend(title='mark')

plt.show()

这篇关于将Pandas crosstab与Seaborn堆叠式Barplots结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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