Home > Software engineering >  Adding data labels ontop of my histogram Python/Matplotlib
Adding data labels ontop of my histogram Python/Matplotlib

Time:12-20

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

CodePudding user response:

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'))
  • Related