自定义 Seaborn histplot 子图中的图例

Wol*_*d72 4 python matplotlib legend seaborn

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

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)
Run Code Online (Sandbox Code Playgroud)

我想为每个子图中的图例条目定义字符串。作为示例,我对第一个子图使用以下代码:

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.')
Run Code Online (Sandbox Code Playgroud)

图例未正确显示(图例条目未绘制,图例标题是色调变量的名称(“statind”)。请注意,我已成功对其他图形使用相同的代码,其中我使用 Seaborn relplots 而不是 histplots 。

Joh*_*anC 12

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

要获得句柄,您可以执行以下操作legend = ax1.get_legend(); handles = legend.legendHandles

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

另请注意,为了确保标签的顺序,设置hue_order. 下面是一些示例代码来展示这些想法:

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()
Run Code Online (Sandbox Code Playgroud)

示例图

  • `legendHandles` 属性在 Matplotlib 3.7 中已弃用,并将在两个小版本后删除。请改用“legend_handles”。 (2认同)