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

matplotlib绘制直方图为每个bin设置不同颜色出现报错如何解决

报错原因

plt.hist()的color参数仅支持为单个数据集设置统一填充色,传入多色列表时需要匹配对应数量的输入数据集,你只有1组输入数据却传入了10个颜色,因此触发参数校验报错:"The 'color' keyword argument must have one color per dataset, but 1 datasets and 10 colors were provided"

解决方案

接收plt.hist()返回的条形补丁对象,逐个为每个bin设置填充色即可,修改后可运行的代码如下:

decades = np.arange(1910, 2020, 10)
colors = ['aqua', 'red', 'gold', 'royalblue', 'darkorange', 'green', 'purple', 'cyan', 'yellow', 'lime']

plt.figure(figsize=(12,7))
n, bins, patches = plt.hist(df.Year, bins=decades)
# 遍历每个条形,设置对应颜色
for patch, color in zip(patches, colors):
    patch.set_facecolor(color)
plt.xticks(decades);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 19:27:04