pythonpython-3.xseabornhistogramkernel-density

How to label the kernel density estimate in histplot


I am plotting a histogram using seaborn, along with a KDE curve and a Gaussian fit, but the instruction label = "KDE fit" in sns.histplot is inappropriately displayed in color, as it seems to refer to the whole histogram... Is there a way to specifically label the KDE curve so as to appear in the legend box as a solid green line (just as the Gaussian fit appears as a dashed red line)?

The full code I used is below:

import numpy as np
import matplotlib.pylab as plt
import seaborn as sns
import scipy.stats as stats
from scipy.stats import norm

# Generating data

np.random.seed(63123) 
data = np.random.normal(loc = 600, scale = 30, size = 20)

# Parameters for histogram plotting

min_val = data.min()
max_val = data.max()
val_width = max_val - min_val
n_bins = 7
bin_width = val_width/n_bins

list_xticks_raw = np.arange(min_val - bin_width/2, max_val + bin_width/2, bin_width).tolist()
list_xticks_round = [round(x) for x in list_xticks_raw]

# Histogram and Gaussian fit plotting

fig = plt.figure(figsize = (4,4))

h = sns.histplot(data = None, x = data , bins = n_bins, binrange=(min_val, max_val), discrete = False, shrink = 1.0,
             stat = "density", element = "bars", color = "green", kde = True, label = "KDE fit")

plt.xlim(min_val - bin_width/2, max_val + bin_width/2) # Define x-axis limits
plt.xticks(list_xticks_round)

mu, sigma = stats.norm.fit(data)
sorted_data = np.sort(data)
gaussian_fit = stats.norm.pdf(sorted_data, mu, sigma)
plt.plot(sorted_data, gaussian_fit, linestyle = "--", color = "red", label = "Gaussian fit")

plt.legend()

plt.show()

enter image description here


Solution

  • Use the line_kws parameter instead of label:

    h = sns.histplot(data = None, x = data , bins = n_bins, binrange=(min_val, max_val), discrete = False, shrink = 1.0,
                 stat = "density", element = "bars", color = "green", kde = True, line_kws={'label': "KDE fit"})
    

    Output:

    enter image description here