【问题标题】:Customizing legend in Seaborn histplot subplots在 Seaborn histplot 子图中自定义图例
【发布时间】:2025-12-04 03:50:01
【问题描述】:

我正在尝试生成一个包含 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)

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

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 relplots 的其他图形而不是直方图。

【问题讨论】:

    标签: python matplotlib seaborn legend


    【解决方案1】:

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

    要获取句柄,您可以使用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()
    

    【讨论】: