Search code examples
pythonpandasmatplotliblabel

Matplotlib - Add value label on bar chart from column in dataframe


I have the following 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

I want to create a bar chart with 'Department' on the X axis, 'Overdue' on the Y axis and the 'Percentage' as a label on each column.

I have written the code below which has produced the following chart:

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));

enter image description here

As you can see, the percentage values do not align with each bar. Please can someone let me know where I am going wrong?

Thanks in advance


Solution

  • Ah I think I see it now. The proper usage is:

    plt.text(x, y, s)
    

    Where your x is index, y is the corrosponding 'Overdue' value (plus an offset to make sure it displays above the bar) and then your s is already in order.

    So that would result something like:

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