You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于pandas DataFrame用seaborn绘制优先级计数堆叠条形图

最简实现方案

不需要复杂的自定义绘图逻辑,基于pandas内置绘图接口(兼容matplotlib、可搭配seaborn美化风格)3步就能出图,代码量最少:

  • 第一步:用pd.crosstab快速统计每个组件下不同优先级的出现次数,自动转成堆叠图需要的宽表结构
  • 第二步:直接调用DataFrame的plot方法指定stacked=True生成堆叠条形图
  • 第三步:按需调整坐标轴、标签、图例即可

完整可运行代码

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

# 可选:套用seaborn风格美化图表
sns.set_theme()

# 对应你给出的示例数据
df = pd.DataFrame({
    'Component': ['Browse Groups', 'Notifications', 'BI', 'BI', 'BI'],
    'Priority': ['Minor', 'Major', 'Major', 'Minor', 'Minor']
})

# 核心逻辑:交叉统计计数
count_table = pd.crosstab(index=df['Component'], columns=df['Priority'])

# 绘制堆叠条形图
ax = count_table.plot(
    kind='bar',
    stacked=True,
    figsize=(8, 5),
    width=0.6
)

# 可选:给每个堆叠块添加居中的数值标注
for bar_group in ax.containers:
    ax.bar_label(bar_group, label_type='center')

# 坐标轴调整
plt.xticks(rotation=0)
plt.ylabel('Priority Count')
plt.xlabel('Component')
plt.tight_layout()
plt.show()

输出效果说明

生成的图表完全匹配你的需求:

  • x轴按顺序展示所有Component分类:Browse Groups、Notifications、BI
  • Browse Groups对应条形仅展示Minor优先级,计数为1
  • Notifications对应条形仅展示Major优先级,计数为1
  • BI对应条形分两层堆叠:下层为Major优先级计数1,上层为Minor优先级计数2,条形总高度为3

注:seaborn原生没有提供直接生成堆叠条形图的封装接口,如果强行用seaborn的barplot循环绘制堆叠层,代码量会比上面的方案高很多,没有必要。

内容的提问来源于stack exchange,提问作者mgn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 18:18:51