Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - Seaborne Linechart Style Causing Duplicate Legend Entries

I'm using seaborn to plot the results of some work using Benford's Law. The plot has two axes: a barplot representing the relative frequency of the digits in the input data, and a linechart representing the expected frequencies from Benford's Law.

As in this question, I used the style=True option so that I could control the style of my line. Unfortunately, this causes a duplicate entry in my legend, which I can't seem to remove. How can I correct the duplicate entry in my legend?

Current code:

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()

And the resulting plot:

enter image description here

question from:https://stackoverflow.com/questions/65866533/seaborne-linechart-style-causing-duplicate-legend-entries

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Not a very nice solution but this works for me when I append it to the end of your plot function:

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

This works because matplotlib ignores any labels beginning with an underscore. Since in your case, labels[1] = "True" is the offender, it has been overwritten as "_True".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...