humanicpanic
humanicpanic

Reputation: 3

How can I add the number of points to a seaborn.histplot?

I wanted to add a number of points (in my case there's 111 points in the data file, so it would be N = 111) under the legend.

sns.histplot(x, stat = 'density', 
         binwidth = 50, 
         kde = True, 
         color = 'red', alpha = .3,
         kde_kws = {'cut': 2, 'bw_adjust': 0.5})
plt.legend(labels=["Sample_1"], 
       fontsize = 16)
plt.xlabel('Age', fontsize=18)
plt.ylabel('Density', fontsize=18)

histogram enter image description here

Upvotes: 0

Views: 1353

Answers (1)

r-beginners
r-beginners

Reputation: 35115

I'm sure there are different approaches to this than mine, but one is to add it to the legend label. The second is to simply add the annotation anywhere. Since no data was provided, I used data from seaborn reference page.

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

penguins = sns.load_dataset("penguins")
hist, bins = np.histogram(penguins['bill_length_mm'].fillna(0))
print(hist,bins)
    
fig, ax = plt.subplots()

ax =sns.histplot(data=penguins, x='bill_length_mm', stat='density', 
         binwidth = 10, 
         kde = True, 
         color = 'red', alpha = .3,
         kde_kws = {'cut': 2, 'bw_adjust': 0.5})
plt.legend(labels=["Sample_1\n N={}".format(max(hist))], fontsize = 16)
plt.text(0.1, 0.9, 'N={}'.format(max(hist)), transform=ax.transAxes)
plt.xlabel('Age', fontsize=18)
plt.ylabel('Density', fontsize=18)

plt.show()

enter image description here

Upvotes: 1

Related Questions