使用matplotlib plt.bar绘制多组柱状图时如何在柱上显示对应数值
你只需接收plt.bar返回的柱子容器对象,遍历每个柱子的坐标与高度信息,配合plt.text即可添加对应数值,全程基于原生plt.bar实现,不需要改动原有绘图的核心逻辑。
完整修改后代码如下:
import numpy as np import matplotlib.pyplot as plt Women = [115, 215, 250, 200] Men = [114, 230, 510, 370] n=4 r = np.arange(n) width = 0.25 # 接收plt.bar返回的柱子对象 bars_women = plt.bar(r, Women, color = 'b', width = width, edgecolor = 'black', label='Women') bars_men = plt.bar(r + width, Men, color = 'g', width = width, edgecolor = 'black', label='Men') # 给Women组柱子添加顶部数值标签 for bar in bars_women: height = bar.get_height() plt.text( bar.get_x() + bar.get_width()/2, # x坐标:柱子水平中心 height, # y坐标:柱子顶部高度 f'{height}', # 显示的数值 ha='center', # 水平居中 va='bottom' # 垂直对齐:文本底部对齐y坐标 ) # 给Men组柱子添加顶部数值标签 for bar in bars_men: height = bar.get_height() plt.text( bar.get_x() + bar.get_width()/2, height, f'{height}', ha='center', va='bottom' ) plt.xlabel("Year") plt.ylabel("Number of people voted") plt.title("Number of people voted in each year") # plt.grid(linestyle='--') plt.xticks(r + width/2,['2018','2019','2020','2021']) plt.legend() # 可根据数值最大值调整y轴上限,避免顶部标签超出画布 plt.ylim(0, max(max(Women), max(Men)) * 1.1) plt.show()
可选调整说明:
- 数值位置调整:如果需要把数值放在柱子中心,将
plt.text的第二个参数改为height/2,同时将va参数改为'center'即可 - 美观优化:如果觉得数值紧贴柱子顶部,可以给y坐标加少量偏移,比如改为
height + 5 - 格式调整:可自行修改
f'{height}'的格式,比如添加单位、保留小数位数等
内容的提问来源于stack exchange,提问作者Zanam
相关产品推荐
相关产品推荐

