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

如何在Python中绘制重复颜色的水平堆叠条形图?

解决水平堆叠条形图固定类别颜色的问题

我明白你的需求了——你希望每个类别(A/B)不管在堆叠中的顺序如何,都保持固定的颜色,但当前代码因为索引匹配和颜色映射的问题没达到效果。下面是修正后的方案,完美实现你想要的效果:

修正后的代码

import numpy as np
from matplotlib import pyplot as plt

dataset = [{'A':19, 'B':55}, {'A':10, 'B':68}]
data_orders = [['B', 'A'], ['A', 'B']]
# 用字典绑定类别和颜色,避免排序导致的对应错误
color_map = {"A": "blue", "B": "green"}

# 计算每个堆叠条形的宽度和起始位置
values = np.array([[data[name] for name in order] for data, order in zip(dataset, data_orders)])
lefts = np.insert(np.cumsum(values, axis=1), 0, 0, axis=1)[:, :-1]
orders = np.array(data_orders)
# 每个主条形的y轴位置
y_positions = np.arange(len(data_orders))

# 循环每个类别,绘制对应颜色的条形
for category, color in color_map.items():
    # 获取当前类别在所有堆叠中的位置:(行索引, 列索引)
    row_indices, col_indices = np.where(orders == category)
    # 精准提取当前类别对应的起始位置、宽度和y轴位置
    bar_left = lefts[row_indices, col_indices]
    bar_width = values[row_indices, col_indices]
    bar_bottom = y_positions[row_indices]  # 关键:匹配每个类别所在的主条形y位置
    
    plt.bar(
        left=bar_left,
        height=0.8,
        width=bar_width,
        bottom=bar_bottom,
        color=color,
        orientation="horizontal",
        label=category
    )

# 优化图表显示
plt.legend(loc="best", bbox_to_anchor=(1.0, 1.00))
plt.subplots_adjust(right=0.85)
plt.yticks(y_positions, ["Group 1", "Group 2"])  # 给y轴添加分组标签
plt.xlabel("Value")
plt.ylabel("Groups")
plt.show()

关键改进点:

  1. 颜色映射更可靠:用字典color_map直接绑定类别和颜色,避免sorted(dataset[0].keys())带来的顺序不确定问题,确保A始终是蓝色,B始终是绿色。
  2. 索引匹配修正:通过row_indices, col_indices获取类别位置后,用y_positions[row_indices]精准对应每个小条形的y轴位置,解决了原代码中bottom参数不匹配的问题。
  3. 代码可读性优化:变量名更直观(比如y_positions代替bottoms),添加了坐标轴标签,让图表更清晰。

运行这段代码后,就能得到你期望的效果:每个类别保持固定颜色,堆叠顺序不影响颜色显示,和你想要的目标图一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:56:46