Search code examples
pythonmatplotlibannotationsbar-charthistogram

Adding data labels ontop of my histogram Python/Matplotlib


i am trying to add data labels values on top of my histogram to try to show the frequency visibly.

This is my code now but unsure how to code up to put the value ontop:

plt.figure(figsize=(15,10))
plt.hist(df['Age'], edgecolor='white', label='d')
plt.xlabel("Age")
plt.ylabel("Number of Patients")
plt.title = ('Age Distrubtion') 

I was wondering if anyone knows the code to do this:

enter image description here


Solution

  • You can use the new bar_label() function using the bars returned by plt.hist().

    Here is an example:

    from matplotlib import pyplot as plt
    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'Age': np.random.randint(20, 60, 200)})
    
    plt.figure(figsize=(15, 10))
    values, bins, bars = plt.hist(df['Age'], edgecolor='white')
    plt.xlabel("Age")
    plt.ylabel("Number of Patients")
    plt.title('Age Distrubtion')
    plt.bar_label(bars, fontsize=20, color='navy')
    plt.margins(x=0.01, y=0.1)
    plt.show()
    

    plt.hist() with plt.bar_label()

    PS: As the age is discrete distribution, it is recommended to explicitly set the bin boundaries, e.g. plt.hist(df['Age'], bins=np.arange(19.999, 60, 5)).