代码之家  ›  专栏  ›  技术社区  ›  indigochild

海上折线图风格导致重复图例条目

  •  1
  • indigochild  · 技术社区  · 5 年前

    我用seaborn来绘制一些使用本福德定律的工作的结果。该图有两个轴:一个条形图表示输入数据中数字的相对频率,一个折线图表示本福德定律的预期频率。

    如in this question ,我用了 style=True 这样我就可以控制我的线条风格。不幸的是,这会导致我的图例中出现重复条目,我似乎无法删除。如何更正图例中的重复条目?

    当前代码:

    def plot(inputdata, digits, y_col_actual, y_col_expected):
    
        plt.rcParams['patch.force_edgecolor']=True
    
        ax1 = sns.barplot(
            data=inputdata,
            x = digits,
            y = y_col_actual,
            color = '#B2E8C2',
            label='Actual Data'
            )
        ax1.set(ylabel='Relative Frequency')
    
        ax2 = sns.lineplot(
            data=inputdata,
            x = digits,
            y = y_col_expected,
            ax = ax1,
            zorder = 5,
            color = 'black',
            style=True,
            dashes=[(2,2)],
            markers=True,
            label='Benfords Law',
            )
        
        plt.show()
    

    以及由此产生的图:

    enter image description here

    0 回复  |  直到 5 年前
        1
  •  1
  •   Kris    5 年前

    这不是一个很好的解决方案,但当我把它附加到你的末尾时,这对我来说很有效 plot 功能:

    handles, labels = ax2.get_legend_handles_labels()
    labels[1] = "_True"
    ax2.legend(handles, labels)
    
    

    这之所以有效,是因为 matplotlib 忽略任何以下划线开头的标签。因为在你的情况下, labels[1] = "True" 如果是罪犯,则已被改写为 "_True" .

        2
  •  1
  •   mwaskom    5 年前

    legend=False 在里面 lineplot ,然后自己添加图例:

    ax = sns.lineplot(
        x=[1, 2, 3], y=[1, 2, 3],
        style=True, dashes=[(2, 2)],
        label="Test", legend=False
    )
    ax.legend()