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

如何通过移动行列值重构DataFrame并绘制stack bar chart?

DataFrame重塑与堆叠柱状图实现方案

一、重塑DataFrame(长表转宽表)

你需要将长格式的DataFrame转换为目标宽格式,用pandas的pivot方法即可快速完成:

1. 构造原始数据(已有DataFrame可跳过)

import pandas as pd

df = pd.DataFrame({
    'idx': [0, 1, 2, 3, 4, 5],
    'bar': ['1~3', '1~3', '4~8', '4~8', 'gt8', 'gt8'],
    'Y': [0, 1, 0, 1, 0, 1],
    'count': [140, 257, 33, 117, 13, 36]
})

2. 执行宽表转换

# 以bar为分组依据,Y的取值作为列名,count作为对应值
pivoted_df = df.pivot(index='bar', columns='Y', values='count').reset_index()
# 移除列名的层级标签,匹配目标格式
pivoted_df.columns.name = None

转换后的pivoted_df结构如下:

bar01
01~3140257
14~833117
2gt81336

二、绘制堆叠柱状图

用matplotlib配合pandas的绘图接口即可生成堆叠柱状图:

import matplotlib.pyplot as plt

# 设置绘图样式(可选)
plt.style.use('seaborn-v0_8')

# 绘制堆叠柱状图,指定x轴为bar列,开启堆叠模式
ax = pivoted_df.plot(kind='bar', stacked=True, x='bar', figsize=(8, 6))

# 添加图表标签与标题
ax.set_title('分组数量堆叠柱状图', fontsize=14)
ax.set_xlabel('分组区间', fontsize=12)
ax.set_ylabel('计数', fontsize=12)

# 给每个堆叠块添加数值标签(可选)
for container in ax.containers:
    ax.bar_label(container, label_type='center', fontsize=10)

# 调整布局防止标签截断
plt.tight_layout()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 04:55:41