我正在使用
seaborn
以及 KDE 曲线和高斯拟合绘制直方图,但是 label = "KDE fit"
中的指令 sns.histplot
以颜色显示不恰当,因为它似乎指的是整个直方图...是有没有办法专门标记 KDE 曲线,以便在 legend
框中显示为绿色实线(就像高斯拟合显示为红色虚线一样)?
我使用的完整代码如下:
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()