【问题标题】:Legend not showing with barless histogram plot in python图例未在 python 中显示无条形直方图
【发布时间】:2021-12-25 11:19:50
【问题描述】:

我正在尝试使用 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')

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

【问题讨论】:

  • 提供样本数据集
  • 我不知道这是否是答案,因为我不知道会发生什么输出,但我认为您可以添加此内容。 ax = sns.kdeplot(data, x="flipper_length_mm", label='kde density')

标签: python matplotlib seaborn histogram legend


【解决方案1】:

您可以通过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()

【讨论】:

  • 非常感谢!这正是我想要的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-12
  • 1970-01-01
相关资源
最近更新 更多