简体   繁体   中英

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在此处输入图像描述

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM