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
相关产品推荐
相关产品推荐

