Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 578
Ruben Vellupillai Avatar asked Feb 04 '26 20:02

Ruben Vellupillai


2 Answers

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

like image 124
JohanC Avatar answered Feb 06 '26 09:02

JohanC


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'))
like image 43
Danyal Imran Avatar answered Feb 06 '26 09:02

Danyal Imran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!