Python 在Seaborn histplot子地块中自定义图例

Python 在Seaborn histplot子地块中自定义图例,python,matplotlib,seaborn,legend,Python,Matplotlib,Seaborn,Legend,我正在尝试生成一个包含4个子地块的图形,每个子地块都是一个Seaborn histplot。地物定义线为: 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) 我想为每个子批次中的图例条目定义字符串。作为示例,我对第一个子批次使用以下代码: sp1=sns.histplot(df

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

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)
我想为每个子批次中的图例条目定义字符串。作为示例,我对第一个子批次使用以下代码:

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.')

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

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

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

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

还要注意的是,为了确保标签的顺序,设置
色调顺序
会有所帮助。下面是一些示例代码来展示这些想法:

导入matplotlib.pyplot作为plt
将numpy作为np导入
作为pd进口熊猫
导入seaborn作为sns
df_dn=pd.DataFrame({'ktau':np.random.randn(4000).cumsum(),
“statid”:np.重复([*'abcd'],1000)})
图,ax1=plt.子批次()
sp1=sns.histplot(df_dn,x=“ktau”,hue=“statid”,hue_顺序=['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
图例。删除()
ax1.legend(句柄,['dep-','ind-','ind+','dep+'],title='Stat.ind.]
plt.show()

谢谢,工作做得很好!