读取excel排序后画的柱状图,要怎么在图上显示每个具体数值?

关注直接上代码:
import pandas as pd
import matplotlib.pyplot as plt
# 解决中文显示问题(根据系统调整字体,如Windows用SimHei,Mac用Heiti TC)
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
# 1. 读取Excel文件(替换为你的文件路径)
# 若文件是csv,再改回pd.read_csv()
df = pd.read_excel("你的数据文件.xlsx") # 注意:需要安装openpyxl库
# 2. 数据处理(确保列名与Excel中一致)
# 假设Excel中列名为 "rtTitle" 和 "NetWeight",否则需修改
df1 = df.groupby(['rtTitle'])['NetWeight'].sum().reset_index()
df2 = df1.sort_values(by=["NetWeight"], ascending=False) # 降序排序
# 3. 绘制柱状图(取前10条数据)
ax = df2.head(10).plot(
kind='bar',
x='rtTitle',
y='NetWeight',
figsize=(10, 6) # 可选:调整图表大小
)
# 4. 在每个柱子顶部添加数值标签
for bar in ax.patches:
# 获取柱子高度(数值)
height = bar.get_height()
# 添加标签
ax.annotate(
f'{height:.0f}', # 显示整数,若需小数可改为 f'{height:.1f}'
(bar.get_x() + bar.get_width()/2, height), # 标签位置(柱子中心顶部)
ha='center', # 水平居中
va='bottom', # 垂直对齐到柱子顶部
fontsize=10 # 标签字体大小
)
# 5. 设置图表标题和坐标轴标签
ax.set_title('各类型的NetWeight总和', fontsize=14)
ax.set_xlabel('rtTitle', fontsize=12)
ax.set_ylabel('NetWeight (Kg)', fontsize=12)
# 6. 调整布局(避免标签被截断)
plt.tight_layout()
# 7. 显示图表
plt.show()