如何在Matplotlib柱状图上添加数值标签?新手技术咨询
给Matplotlib柱状图添加数值标签的实现方法
我是一名新手,希望在下方Matplotlib绘制的柱状图的每个柱子上添加对应字典的数值作为标签,请问正确的语法是什么?相关代码如下:
import pandas as pd import matplotlib.pyplot as plt df=pd.read_excel('aspire_2408.xls') started=len(df.loc[df['Aspire year-end reflection (FY22)'] == 'Started']) completed = len(df.loc[df['Aspire year-end reflection (FY22)'] == 'Complete']) not_started = len(df.loc[df['Aspire year-end reflection (FY22)'] == 'Not Started']) data = {'Not Started':not_started, 'Started':started, 'Completed':completed} courses = list(data.keys()) values = list(data.values()) fig = plt.figure(figsize = (10, 5)) # creating the bar plot plt.bar(courses, values, color =['red','blue','green'],width = 0.4) plt.xlabel("Year End Review Completion Status") plt.ylabel("No Users") plt.title("Aspire Year End Review") plt.show()
具体实现步骤
要给每个柱子加上对应数值标签,核心是用plt.text()在柱子的合适位置绘制文本。直接看修改后的完整代码:
修改后的代码
import pandas as pd import matplotlib.pyplot as plt df=pd.read_excel('aspire_2408.xls') started=len(df.loc[df['Aspire year-end reflection (FY22)'] == 'Started']) completed = len(df.loc[df['Aspire year-end reflection (FY22)'] == 'Complete']) not_started = len(df.loc[df['Aspire year-end reflection (FY22)'] == 'Not Started']) data = {'Not Started':not_started, 'Started':started, 'Completed':completed} courses = list(data.keys()) values = list(data.values()) fig = plt.figure(figsize = (10, 5)) # 创建柱状图,把返回的柱子对象存起来 bars = plt.bar(courses, values, color=['red','blue','green'], width=0.4) # 遍历每个柱子添加标签 for bar in bars: # 获取柱子的高度(就是对应数值) height = bar.get_height() # 在柱子顶部居中位置写数值 plt.text( bar.get_x() + bar.get_width()/2, # 水平居中位置 height, # 垂直位置在柱子顶部 f'{height}', # 要显示的数值 ha='center', # 水平居中对齐 va='bottom' # 垂直方向靠下,紧贴柱子顶部 ) plt.xlabel("Year End Review Completion Status") plt.ylabel("No Users") plt.title("Aspire Year End Review") plt.show()
核心逻辑说明
- 先把
plt.bar()的结果赋值给bars,这样能拿到每个柱子的实例对象 - 循环遍历每个柱子:
bar.get_height():获取当前柱子对应的数值,也就是我们要展示的标签内容bar.get_x() + bar.get_width()/2:计算柱子的水平中心,保证标签不会偏左偏右ha='center'和va='bottom':控制文本的对齐方式,让标签刚好贴在柱子顶部中间
如果想让标签显示在柱子内部(比如柱子比较高的时候),可以调整垂直位置和对齐方式,比如:
plt.text( bar.get_x() + bar.get_width()/2, height - 1, # 比柱子顶部低1个单位 f'{height}', ha='center', va='top', color='white' # 换成白色更显眼 )
内容的提问来源于stack exchange,提问作者Stefano
相关产品推荐
相关产品推荐

