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

Python pandas绘制柱状图如何实现部分列堆叠、部分列不堆叠?

混合堆叠柱状图实现方案

要实现同一x轴维度下同时展示独立柱子和堆叠柱子的效果,核心是手动控制不同组柱子的水平位置,复用同一个绘图轴对象避免生成多张图表。

完整可运行代码

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

# 构造示例数据,可替换为你自己的final_df
data = {
    'Date': ['2021-08-20', '2021-08-11', '2021-08-07', '2021-08-19', '2021-08-31'],
    'column1': [19, 15, 5, 25, 6],
    'column2': [30, 25, 10, 36, 6],
    'column3': [11, 11, 5, 16, 6],
    'column4': [8, 4, 0, 9, 0]
}
final_df = pd.DataFrame(data)

# 配置基础绘图参数
x = np.arange(len(final_df))  # 每个日期对应的x轴基准坐标
bar_width = 0.25  # 单根柱子的宽度,可根据显示效果调整
fig, ax = plt.subplots(figsize=(20, 5))

# 绘制独立柱子column1,位置在基准坐标左侧偏移一个宽度
ax.bar(x - bar_width, final_df['column1'], width=bar_width, label='column1')
# 绘制独立柱子column2,位置在基准坐标处
ax.bar(x, final_df['column2'], width=bar_width, label='column2')
# 绘制堆叠柱底部column3,位置在基准坐标右侧偏移一个宽度
ax.bar(x + bar_width, final_df['column3'], width=bar_width, label='column3')
# 绘制堆叠柱顶部column4,位置和底部柱一致,通过bottom参数实现堆叠
ax.bar(x + bar_width, final_df['column4'], width=bar_width, bottom=final_df['column3'], label='column4')

# 配置坐标轴和图例
ax.set_xticks(x)
ax.set_xticklabels(final_df['Date'], rotation=90)
ax.legend()
fig.tight_layout()  # 自动调整布局避免标签被截断

plt.show()

实现说明

  • 每个日期对应三组展示内容:column1、column2、堆叠的column3+column4,通过对三组内容分别设置不同的x轴偏移量,避免柱子重叠
  • 堆叠效果通过给上层柱子指定bottom参数为下层柱子的数值实现
  • 所有绘图操作都复用同一个ax对象,保证所有内容输出在同一张图表中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:24:03