在Seaborn直方图子图中自定义图例 [英] Customizing legend in Seaborn histplot subplots

查看:68
本文介绍了在Seaborn直方图子图中自定义图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一个包含4个子图的图形,每个子图都是Seaborn直方图.图形定义行是:

I am trying to generate a figure with 4 subplots, each of which is a Seaborn histplot. The figure definition lines are:

fig,axes=plt.subplots(2,2,figsize=(6.3,7),sharex=True,sharey=True)
(ax1,ax2),(ax3,ax4)=axes
fig.subplots_adjust(wspace=0.1,hspace=0.2)

我想为每个子图中的图例条目定义字符串.举例来说,我将以下代码用于第一个子图:

I would like to define strings for legend entries in each of the subplots. As an example, I am using the following code for the first subplot:

sp1=sns.histplot(df_dn,x="ktau",hue="statind",element="step", stat="density",common_norm=True,fill=False,palette=colvec,ax=ax1)
ax1.set_title(r'$d_n$')
ax1.set_xlabel(r'max($F_{a,max}$)')
ax1.set_ylabel(r'$\tau_{ken}$')
legend_labels,_=ax1.get_legend_handles_labels()
ax1.legend(legend_labels,['dep-','ind-','ind+','dep+'],title='Stat.ind.')

图例未正确显示(未绘制图例条目,图例标题是色相变量的名称("statind").请注意,我已成功将相同的代码用于使用Seaborn的其他图形代替历史记录.

The legend is not showing correctly (legend entries are not plotted and the legend title is the name of the hue variable ("statind"). Please note I have successfully used the same code for other figures in which I used Seaborn relplots instead of histplots.

推荐答案

主要问题是 ax1.get_legend_handles_labels()返回空列表(请注意,第一个返回值是句柄,第二个返回值是句柄将是标签).至少对于seaborn的 histplot()的当前版本(0.11.1).

The main problem is that ax1.get_legend_handles_labels() returns empty lists (note that the first return value are the handles, the second would be the labels). At least for the current (0.11.1) version of seaborn's histplot().

要获取句柄,可以执行 legend = ax1.get_legend();.handles = legend.legendHandles .

To get the handles, you can do legend = ax1.get_legend(); handles = legend.legendHandles.

要重新创建图例,首先需要删除现有的图例.然后,可以从一些手柄开始创建新的图例.

To recreate the legend, first the existing legend needs to be removed. Then, the new legend can be created starting from some handles.

还请注意,要确保标签的顺序,它有助于设置 hue_order .以下是一些示例代码来展示这些想法:

Also note that to be sure of the order of the labels, it helps to set hue_order. Here is some example code to show the ideas:

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

df_dn = pd.DataFrame({'ktau': np.random.randn(4000).cumsum(),
                      'statind': np.repeat([*'abcd'], 1000)})

fig, ax1 = plt.subplots()
sp1 = sns.histplot(df_dn, x="ktau", hue="statind", hue_order=['a', 'b', 'c', 'd'],
                   element="step", stat="density", common_norm=True, fill=False, ax=ax1)
ax1.set_title(r'$d_n$')
ax1.set_xlabel(r'max($F_{a,max}$)')
ax1.set_ylabel(r'$\tau_{ken}$')
legend = ax1.get_legend()
handles = legend.legendHandles
legend.remove()
ax1.legend(handles, ['dep-', 'ind-', 'ind+', 'dep+'], title='Stat.ind.')
plt.show()

这篇关于在Seaborn直方图子图中自定义图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆