Search code examples
pythonmatplotlibseabornseaborn-objects

seaborn legend (functions vs. object)


when using seaborn functions I can get all handles and labels:

p=(
sns.scatterplot(data=peng, x='island', y='bill_length_mm', hue='species', style='sex')
)
print(type(p))
h, l = p.get_legend_handles_labels()
print(l)

['species', 'Adelie', 'Chinstrap', 'Gentoo', 'sex', 'Male', 'Female']

but when using seaborn object I get empty list:

p=(
so.Plot(data=peng, x='island', y='bill_length_mm', color='species',
        pointsize='species', fill='sex', marker='sex')
    .layout(size=(6,5))
    .add(so.Dots(stroke=0.5), so.Jitter(0.4))
    .scale(marker=["o", (6, 2, 1)], pointsize=(6,8), color='flare')
    .plot()
)

ax, = p._figure.axes
h, l = ax.get_legend_handles_labels()
print(l)

[]

is there any method than can help in this issue?


Solution

  • The seaborn objects API adds the legend(s) to the figure instead of the ax. You can loop over p._legend_contents to get to the handles labels:

    p=(
    so.Plot(data=peng, x='island', y='bill_length_mm', color='species',
            pointsize='species', fill='sex', marker='sex')
        .layout(size=(6,5))
        .add(so.Dots(stroke=0.5), so.Jitter(0.4))
        .scale(marker=["o", (6, 2, 1)], pointsize=(6,8), color='flare')
        .plot()
    )
    
    for key, artists, labels in p._legend_contents:
        print(f'{key[0]}: {labels}')
    

    Output:

    species: ['Adelie', 'Gentoo', 'Chinstrap']
    sex: ['male', 'female']