如何在Matplotlib多柱状图的柱间上方添加bar_label?
解决方法:在双柱组中间上方添加差值标签
要实现将offer_difference作为标签放在每组两个柱子的中间上方,核心是手动计算标签的位置,利用plt.text()逐个添加。修改后的完整代码如下:
import matplotlib.pyplot as plt import numpy as np name = ['Jay', 'Bert', 'Mike', 'Aaron'] name_len = np.arange(len(name)) best_offer = [0.21, 0.34, 0.6, 0.8] best_offer_est = [0.25, 0.4, 0.5, 0.75] offer_difference = [16, 15, -20, -6.6] f = plt.figure() f.set_figwidth(20) f.set_figheight(10) # 绘制两组柱状图 bar1 = plt.bar(name_len - 0.2, best_offer, 0.4, label='Best Offer') bar2 = plt.bar(name_len + 0.2, best_offer_est, 0.4, label='Best Offer Est', edgecolor='gray', linewidth=4) # 计算每组柱子的最大高度,作为标签垂直位置的基准 max_heights = np.max([best_offer, best_offer_est], axis=0) # 逐个添加差值标签到每组柱子中间上方 for x, diff, height in zip(name_len, offer_difference, max_heights): # 调整y轴偏移量,避免标签与柱子重叠 plt.text(x, height + 0.02, f'{diff}%', ha='center', fontsize=12, fontweight='bold') plt.xticks(name_len, name, rotation=45, ha='right') plt.legend() plt.show()
关键细节说明
- 标签位置计算:每组两个柱子的x坐标分别是
name_len - 0.2和name_len + 0.2,中间位置就是name_len,以此作为标签的x轴坐标。 - 垂直位置调整:取每组两个柱子的最大高度,在此基础上增加0.02的偏移量,确保标签位于柱子上方且不重叠。
- 对齐与样式:
ha='center'保证标签在x轴方向居中,可通过fontsize、fontweight调整标签样式。 - 修正原代码错误:原
plt.xticks中的label=offer_difference是无效参数,已删除,仅保留刻度位置和对应名称的设置。
内容的提问来源于stack exchange,提问作者PoorPythonProgrammer
相关产品推荐
相关产品推荐

