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:

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

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)).
The plt.ylabel() comes with a parameter called loc that can be used to define a label's position:
plt.ylabel("Age", loc="top")
If you want manual control, you can use the **kwargs argument to pass in Text object (documentation) which can take in x and y co-ordinate values to place text.
plt.ylabel("Age", text(x=100, y=200, rotation='horizontal'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With