我正在使用seaborn绘制直方图,以及KDE曲线和高斯拟合,但sns.histplot中的指令label = "KDE fit"显示为不适当的 colored颜色 ,因为它似乎引用了整个直方图……有没有办法特别标记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()

enter image description here

推荐答案

使用line_kws参数而不是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"})

输出:

enter image description here

Python-3.x相关问答推荐

如何将CSV或FDF数据解析到Python词典并注入到模板PDF表单中?

Pandas -我们如何在一行中应用多个要求

python3,将整数转换为字节:对于小整数使用 to_bytes() 有哪些替代方法?

如何提高 snowpark 程序的性能?

需要找到完全匹配并使用正则表达式替换

pip install saxonche v 12.1.0 产生 FileNotFoundError

单击图形时 plotly graph_objects 持久性数据

如何从形状汇总图中提取实际值

列出相同索引的Pandas

将元组列表转换为以整个元组为键的字典列表

获取以特定字母开头的姓氏

Python - For 循环数百万行

为什么 virtualenv 会有效地禁用 Python 3 制表符补全?

从大字典中弹出 N 项的最快方法

根据条件过滤元组列表

混合全局/参数和名为top的函数的奇怪python行为

警告:请使用 tensorflow/models 中的官方/mnist/dataset.py 等替代方案

是否可以在每个路由的基础上限制 Flask POST 数据大小?

如何在python中创建代码对象?

命名参数可以与 Python 枚举一起使用吗?