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

Matplotlib能否实现阶梯式堆叠面积图?

阶梯式堆叠面积图实现方案

核心思路是通过逐层计算堆叠边界,结合matplotlib的stairs方法自带的填充能力实现阶梯效果,完全匹配累计类数据的展示逻辑。

实现步骤

1. 导入依赖并准备测试数据

import numpy as np
import matplotlib.pyplot as plt

# 示例X轴区间端点,长度为n+1(对应n个数值区间)
x_edges = [1, 2, 3, 4, 5, 6, 7]
# 3个类别的数值,长度为n
y1 = np.array([2, 3, 1, 4, 2, 3])
y2 = np.array([1, 2, 3, 2, 4, 1])
y3 = np.array([3, 1, 2, 3, 1, 2])

2. 逐层绘制阶梯堆叠层

fig, ax = plt.subplots(figsize=(10, 6))
# 自定义每层配色
colors = ["#1f77b4", "#ff7f0e", "#2ca02c"]
layers = [y1, y2, y3]
labels = ["类别A", "类别B", "类别C"]

# 初始堆叠底部为0
bottom = np.zeros_like(y1)

for idx, layer in enumerate(layers):
    upper = bottom + layer
    # 绘制阶梯填充层,step='post'符合累计数据从当前节点生效的逻辑
    ax.stairs(
        values=upper,
        edges=x_edges,
        baseline=bottom,
        fill=True,
        color=colors[idx],
        alpha=0.8,
        step="post",
        label=labels[idx]
    )
    # 更新下一层的堆叠底部
    bottom = upper

# 补充图表样式
ax.legend()
ax.set_xlabel("X轴指标")
ax.set_ylabel("累计数值")
ax.set_title("阶梯式堆叠面积图")
plt.grid(alpha=0.3)
plt.show()

关键说明

  • 如果你的原始X轴是离散节点而非区间端点,可以直接在原始X数组末尾追加一个递增值作为最后一个区间的结束端点即可,比如x_edges = np.append(x_nodes, x_nodes[-1] + 1)
  • step参数可根据需求调整:pre为区间左对齐阶梯、post为区间右对齐阶梯、mid为中点对齐阶梯
  • 如果需要调整堆叠顺序,只需要调换layers列表里的数值序列顺序即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:36:04