Matplotlib柱状图添加边框异常:仅首对柱状图生效
解决Matplotlib柱状图仅第一对柱子显示边框的问题
我看到你参考官方示例做柱状图时遇到了边框只显示在第一对柱子上的问题,这个情况在Matplotlib的部分旧版本里确实会出现——当你在bar()函数里同时使用yerr参数时,edgecolor和linewidth的设置并不会自动应用到所有柱状条上,这是因为误差线的渲染逻辑导致参数没有传递到所有子元素。
这里有两种简单的解决办法:
方法一:手动遍历所有柱子设置边框属性
你可以在创建完柱状条对象后,逐个遍历每个柱子,单独设置边框颜色和宽度。修改后的代码如下:
""" ======== Barchart ======== A bar plot with errorbars and height labels on individual bars """ import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) men_std = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() # 先移除bar函数里的linewidth和edgecolor参数 rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std) women_means = (25, 32, 34, 20, 25) women_std = (3, 5, 2, 3, 3) rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std) # 遍历每个柱子,设置边框 for rect in rects1: rect.set_edgecolor('black') rect.set_linewidth(1) for rect in rects2: rect.set_edgecolor('black') rect.set_linewidth(1) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(ind + width / 2) ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) def autolabel(rects): """Attach a text label above each bar displaying its height""" for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) plt.show()
方法二:升级Matplotlib版本
这个问题在Matplotlib 3.0及以上的版本中已经被官方修复了,如果你可以升级你的库,直接执行以下命令升级后,原来的代码就能正常显示所有柱子的边框了:
pip install --upgrade matplotlib
这样修改后,所有柱状条都会显示你需要的黑色边框啦。
内容的提问来源于stack exchange,提问作者davidsaezsan
相关产品推荐
相关产品推荐

