首页 > 解决方案 > 图例未在 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')

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

标签: pythonmatplotlibseabornhistogramlegend

解决方案


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

sns.kdeplot 缩放为概率,带有图例


推荐阅读