python 中的无条直方图未显示图例

Legend not showing with barless histogram plot in python

我正在尝试使用 histplot 函数在 seaborn 中绘制一个 kde 图,然后按以下方式删除直方图的条形图(请参阅已接受答案的最后一部分 ):

fig, ax = plt.subplots()
sns.histplot(data, kde=True, binwidth=5,  stat="probability", label='data1', kde_kws={'cut': 3})

之所以使用histplot而不是kdeplot是因为我需要设置一个特定的binwidth。我遇到的问题是无法打印出图例,这意味着

ax.legend(loc='best')

什么都不做,我收到以下消息:No handles with labels found to put in legend.

我也试过

handles, labels = ax.get_legend_handles_labels()
plt.legend(handles, labels, loc='best')

但没有结果。有人知道这里发生了什么吗?提前致谢!

您可以通过 line_kws={'label': ...} 参数为 kde 行添加标签。

sns.kdeplot不能直接使用,因为目前只能选择默认缩放(密度)

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

data = np.random.normal(0.01, 0.1, size=10000).cumsum()
ax = sns.histplot(data, kde=True, binwidth=5, stat="probability", label='data1',
                  kde_kws={'cut': 3}, line_kws={'label': 'kde scaled to probability'})
ax.containers[0].remove() # remove the bars of the histogram
ax.legend()
plt.show()