python - 图例未在 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()
推荐阅读
- python - 在 python 3 中以二进制模式打开带有通用换行符的文件
- javascript - 额外的行出现在网格/表格中
- ios - 我将地图设置为旋转到用户位置。如何允许用户与地图交互?
- ios - didSelectRowAt 不适用于我的 UITableViewController
- c# - 使用 Cookie 在 Web API 中配置域
- python - 如何更新代码以显示随机游走?
- excel - 运行时错误 53 file not found for some files in directory
- charts - 谷歌图表没有占用 100% 的空间
- java - android.view.accessibility.AccessibilityNodeInfo.setText 致命异常:java.lang.IndexOutOfBoundsException
- python - Ray 集群配置 file_mounts 部分不允许工作节点启动