Search code examples
pythonmatplotlibseabornseaborn-0.12.x

The labels are not same as figure in lineplot



comp_fib1=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,3,6,7,7,11,18,30,47,88,143]
comp_fib2=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]


import matplotlib.pyplot as plt
import seaborn as sns

sns.lineplot(
    data=[comp_fib1,comp_fib2],legend=False,markers=['*','o'],palette='colorblind')
plt.legend(title='Fibonacci series',loc='upper left',labels={'fib1','fib2'})
plt.gca().get_legend_handles_labels()

This is the image of the figure formed

I used the above code, I customized the handles but they are not the same as the figure. Is there any way that i can get the right handle with customized name?


Solution

  • Maybe this is a relevant question.

    As a simple workaround, I found that using Pandas helps alleviate the need to edit the legend labels via plt (which breaks the final rendering). You just have to create a DataFrame with two columns, the names of which are the labels you want to show inside the legend. Seaborn will use these column names as legend labels by default.

    import pandas as pd
    
    df = pd.DataFrame({'fib1': comp_fib1, 'fib2': comp_fib2})
    ax = sns.lineplot(data=df, legend='full', markers=['*', 'o'], palette='colorblind')
    ax.legend(title='Fibonacci series', loc='upper left')
    

    enter image description here