如何修改循环构建的Matplotlib分组柱状图的柱子颜色
修改Matplotlib分组柱状图的柱子颜色
你可以通过在循环绘制柱状图时,给ax.bar()方法指定color参数来实现自定义颜色,具体实现如下:
- 先定义好你需要的颜色列表;
- 在循环中利用
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
相关产品推荐
相关产品推荐

