python - 使用 pandas 交叉表创建条形图

标签 python pandas matplotlib seaborn bar-chart

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

我首先在 pandas 中生成了一个交叉表,如下所示:

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 创建一个堆叠条形图以实现一致性,这就是我在其余图表中使用的内容。然而,我很难做到这一点,因为我无法为交叉表编制索引。

我已经能够使用 .plot.barh(stacked=True) 在 pandas 中制作我想要的情节,但 seaborn 没有运气。我有什么想法可以做到这一点吗?

最佳答案

  • 正如您所说,您可以使用 pandas 创建堆积条形图。你想要一个“seaborn plot”的论点是无关紧要的,因为每个 seaborn plot 和每个 pandas plot 最后都只是 matplotlib 对象,因为这两个库的绘图工具只是 matplotlib 包装器。
  • 这是一个完整的解决方案(使用来自@andrew_reece 的回答的数据创建)。
  • python 3.8.11pandas 1.3.2matplotlib 3.4.3seaborn 0.11 中测试。 2
import numpy as np 
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

n = 500
np.random.seed(365)
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)
    
ax = ct.plot(kind='bar', stacked=True, rot=0)
ax.legend(title='mark', bbox_to_anchor=(1, 1.02), loc='upper left')

# add annotations if desired
for c in ax.containers:
    
    # set the bar label
    ax.bar_label(c, label_type='center')

enter image description here

关于python - 使用 pandas 交叉表创建条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43544694/

相关文章:

python - Pandas - 每个点具有不同颜色图例的散点图

python - 三层饼图 matplotlib - 如何 "prettify"

python - 如何向 pandas 数据框添加新记录

Python:按条件删除重复项

python - False 不应被视为 0

python - 将多个字符串列转换为整数列表

matplotlib - 值错误 : Floating point image RGB values must be in the 0. .1 范围。使用 matplotlib 时

python - ImageGrid 中的颜色条标签 matplotlib

python - MongoDB 计算数组中的不同项

python - 将 YAML 文件读取为列表