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

如何修改循环构建的Matplotlib分组柱状图的柱子颜色

修改Matplotlib分组柱状图的柱子颜色

你可以通过在循环绘制柱状图时,给ax.bar()方法指定color参数来实现自定义颜色,具体实现如下:

  1. 先定义好你需要的颜色列表;
  2. 在循环中利用multiplier变量作为索引,从颜色列表中取出对应颜色传递给bar()方法。

修改后的完整代码:

import numpy as np
import matplotlib.pyplot as plt

species = ("Adelie", "Chinstrap", "Gentoo")
penguin_means = {
    'Bill Depth': (18.35, 18.43, 14.98),
    'Bill Length': (38.79, 48.83, 47.50),
    'Flipper Length': (189.95, 195.82, 217.19),
}

# 自定义颜色列表
colors = ['lightsalmon', 'lightseagreen', 'darkseagreen', 'mediumorchid']

x = np.arange(len(species))  # 标签位置
width = 0.25  # 柱子宽度
multiplier = 0

fig, ax = plt.subplots(layout='constrained')

for attribute, measurement in penguin_means.items():
    offset = width * multiplier
    # 为当前属性的柱子指定对应颜色
    rects = ax.bar(x + offset, measurement, width, label=attribute, color=colors[multiplier])
    ax.bar_label(rects, padding=3)
    multiplier += 1

ax.set_ylabel('Length (mm)')
ax.set_title('Penguin attributes by species')
ax.set_xticks(x + width, species)
ax.legend(loc='upper left', ncols=3)
ax.set_ylim(0, 250)

plt.show()

补充说明

你的颜色列表包含4种颜色,但当前仅需绘制3类属性的柱子,因此只会用到前3种颜色,第4种颜色会被预留,若后续新增属性,会自动使用该颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 05:24:56