使用 pandas 交叉表创建条形图

2024-08-21Python开发问题
6

本文介绍了使用 pandas 交叉表创建条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

我首先在 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

我想使用海运为全余创建一个堆叠的条形图,这就是我在我的图表的睡觉中使用的。但是,我很难做到这一点,因为我无法为交叉表编制索引。

我已经能够使用.plot.barh(stacked=True)在 pandas 身上制作我想要的情节,但在海运方面没有运气。你知道我该怎么做吗?

推荐答案

  • 如您所说,您可以使用 pandas 创建堆叠条形图。您想要有一个海运绘图的论点是无关紧要的,因为每个海运绘图和每个 pandas 绘图最终都只是matplotlib对象,因为这两个库的绘图工具仅仅是matplotlib包装器。
  • 这里有一个完整的解决方案(使用@Andrew_Reess的答案创建数据)。
  • 测试于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')

这篇关于使用 pandas 交叉表创建条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10