为条形图添加样式细节:误差线加短划线及背景分区着色
Matplotlib条形图问题解决方案
原代码如下:
x = [1, 2, 3, 4, 5, 6] y = [-0.015, 0.386, -0.273, -0.091, 0.955, 1.727] errors = [0.744, 0.954, 0.737, 0.969, 0.848, 0.460] plt.figure(figsize=(8, 4)) plt.bar(x, y, yerr=errors, align='center', alpha=0.5, color='grey') plt.xticks((0, 1, 2, 3, 4, 5, 6, 7), ('', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', '')) plt.ylim((-3, 3)) plt.show()
问题1:为误差线段添加顶部和底部的短划线
直接在plt.bar()函数中添加capsize参数,设置一个合适的数值(比如5),就能给误差线两端加上短帽线:
plt.bar(x, y, yerr=errors, align='center', alpha=0.5, color='grey', capsize=5)
问题2:按y值分区着色背景
使用axhspan()函数绘制水平背景色块,注意要先画背景再画条形图(或者通过zorder参数调整层级),避免背景遮挡条形图。具体实现如下:
plt.figure(figsize=(8, 4)) ax = plt.gca() # 绘制三个区间的背景色,alpha设置透明度避免遮挡条形图 ax.axhspan(-3, -0.8, facecolor='red', alpha=0.2) ax.axhspan(-0.8, 0.8, facecolor='yellow', alpha=0.2) ax.axhspan(0.8, 3, facecolor='green', alpha=0.2) # 绘制带误差线帽的条形图 plt.bar(x, y, yerr=errors, align='center', alpha=0.5, color='grey', capsize=5) plt.xticks((0, 1, 2, 3, 4, 5, 6, 7), ('', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', '')) plt.ylim((-3, 3)) plt.show()
完整修改后的代码
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5, 6] y = [-0.015, 0.386, -0.273, -0.091, 0.955, 1.727] errors = [0.744, 0.954, 0.737, 0.969, 0.848, 0.460] plt.figure(figsize=(8, 4)) ax = plt.gca() # 背景分区着色 ax.axhspan(-3, -0.8, facecolor='red', alpha=0.2) ax.axhspan(-0.8, 0.8, facecolor='yellow', alpha=0.2) ax.axhspan(0.8, 3, facecolor='green', alpha=0.2) # 带误差线帽的条形图 plt.bar(x, y, yerr=errors, align='center', alpha=0.5, color='grey', capsize=5) plt.xticks((0, 1, 2, 3, 4, 5, 6, 7), ('', 'I1', 'I2', 'I3', 'I4', 'I5', 'I6', '')) plt.ylim((-3, 3)) plt.show()
内容的提问来源于stack exchange,提问作者LJG
相关产品推荐
相关产品推荐

