1

I have a dataset of used cars. I have made a histogram plot for the count of cars by their age (in months).

sns.distplot(df['Age'],kde=False,bins=6)

And the plot looks something like this:

enter image description here

Is there any way I can depict the frequency values of each bin in the plot itself

PS: I know I can fetch the values using the numpy histogram function which is

np.histogram(df['Age'],bins=6)

Basically I want the plot to look somewhat like this I guess so:

enter image description here

dm2
  • 4,053
  • 3
  • 17
  • 28
Sudarshan
  • 13
  • 1
  • 5

1 Answers1

0

You can iterate over the patches belonging to the ax, get their position and height and use these to create annotations.

import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

sns.set_style()
df = pd.DataFrame({'Age': np.random.triangular(1, 80, 80, 1000).astype(np.int)})
ax = sns.distplot(df['Age'], kde=False, bins=6)

for p in ax.patches:
    ax.annotate(f'{p.get_height():.0f}\n',
                (p.get_x() + p.get_width() / 2, p.get_height()), ha='center', va='center', color='crimson')
plt.show()

example plot

JohanC
  • 71,591
  • 8
  • 33
  • 66