图例未在 python 中用无条直方图显示

2023-12-10

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

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

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


您可以通过以下方式添加 kde 行的标签line_kws={'label': ...}范围。

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

sns.kdeplot scaled to probability, with legend

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

图例未在 python 中用无条直方图显示 的相关文章

随机推荐