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

如何修改Matplotlib堆叠柱状图中条形的自定义颜色?

解决Matplotlib堆叠柱状图自定义颜色问题

你的核心问题是定义了colors列表但未在绘图时调用,且未将颜色与对应类别绑定。根据需求:"Below"和"Above"设为lightgrey,"Middle"设为gray,以下是两种可行的修改方案:

方案一:颜色字典映射(推荐)

用字典直接绑定类别与对应颜色,避免因顺序问题导致颜色错位,可读性更强:

import matplotlib.pyplot as plt
import numpy as np

species = (
    "MP 1",
    "MP 2",
    "MP 3",
)

max_A2M4 = 2260

weight_counts = {
    "Below":    np.array([76, 100, 24]) / max_A2M4*100,
    "Middle":   np.array([1600-76, 1779-100, max_A2M4-24]) / max_A2M4*100,
    "Above":    np.array([max_A2M4-1600, max_A2M4-1779, 0]) / max_A2M4*100,
}
width = 0.5

fig, ax = plt.subplots()
bottom = np.zeros(3)

# 建立类别-颜色映射字典
color_map = {
    "Below": "lightgrey",
    "Middle": "gray",
    "Above": "lightgrey"
}

for category, weight_count in weight_counts.items():
    # 在bar函数中指定color参数,调用对应颜色
    p = ax.bar(species, weight_count, width, label=category, bottom=bottom, color=color_map[category])
    bottom += weight_count

ax.set_title("Window settings")
ax.legend(loc="upper right")
ax.set_ylim(-5,105)

plt.show()

方案二:列表循环绑定

若习惯用列表管理颜色,需确保列表顺序与字典键的顺序一致(Python 3.7+字典默认保留插入顺序):

import matplotlib.pyplot as plt
import numpy as np

species = (
    "MP 1",
    "MP 2",
    "MP 3",
)

max_A2M4 = 2260

weight_counts = {
    "Below":    np.array([76, 100, 24]) / max_A2M4*100,
    "Middle":   np.array([1600-76, 1779-100, max_A2M4-24]) / max_A2M4*100,
    "Above":    np.array([max_A2M4-1600, max_A2M4-1779, 0]) / max_A2M4*100,
}
width = 0.5

fig, ax = plt.subplots()
bottom = np.zeros(3)

colors = ['lightgrey', 'gray', 'lightgrey']

# 同时遍历类别数据和颜色列表
for (category, weight_count), color in zip(weight_counts.items(), colors):
    p = ax.bar(species, weight_count, width, label=category, bottom=bottom, color=color)
    bottom += weight_count

ax.set_title("Window settings")
ax.legend(loc="upper right")
ax.set_ylim(-5,105)

plt.show()

关键说明

两种方案的核心都是在ax.bar()中添加color参数,指定每个类别的自定义颜色,这是之前代码缺失的关键步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 03:13:13