首页 > 解决方案 > Matplotlib - 从数据框中的列在条形图上添加值标签

问题描述

我有以下df(test2):

    Department                    Assignment Status     Overdue      Percentage
2   Business Services             Overdue               393          2.05
5   Operations                    Overdue               4651         3.67
8   Quality Assurance             Overdue               650          2.16
11  Quality Control               Overdue               1046         2.43
14  R&D Operations                Overdue               1645         2.53

我想创建一个条形图,X 轴为“部门”,Y 轴为“过期”,每列上的标签为“百分比”。

我编写了下面的代码,生成了以下图表:

x=test2['Department']
y=test2['Overdue']
z=test2['Percentage']

my_colors = 'rgbkymc'

figx = plt.figure(figsize=(10,5))
plt.bar(x, y, color=my_colors)
figx.suptitle('Overdue Training Assignments by Department', fontsize=20)
plt.xlabel('Department', fontsize=14)
plt.ylabel('Overdue Count', fontsize=14)

for index, value in enumerate(z):
    plt.text(value, index, str(value));

在此处输入图像描述

如您所见,百分比值与每个条不对齐。请问有人可以让我知道我哪里出错了吗?

提前致谢

标签: pythonpandasmatplotliblabel

解决方案


啊,我想我现在看到了。正确的用法是:

plt.text(x, y, s)

x的索引y是对应的“过期”值(加上一个偏移量以确保它显示在条形上方),然后你s就已经正常了。

所以这将导致类似:

for index, value in enumerate(z):
    plt.text(index, y[index] + offset, str(value))

推荐阅读