How can I customize the legend with Seaborn 0.12 objects?
Asked Answered
L

1

5

The new Seaborn objects (v 0.12) are great but I struggle to deal with legend customization. Especially when using matplotlib to define subplots. My code:

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(3.5, 3.5), gridspec_kw={'width_ratios':[1.5,1]}, dpi=dpi)
(
     so.Plot(sert_neurons, x='mod_index_late', y='opto_mod_roc', color='sig_modulation')
     .add(so.Dot(pointsize=2))
     .add(so.Line(color='k'), so.PolyFit(order=1), color=None)
     .limit(x=[-1, 1], y=[-1, 1])
     .label(x='Spontaneous 5-HT modulation', y='Task evoked 5-TH modulation')
     .on(ax1)
     .plot()
)
plt.tight_layout()
sns.despine(trim=True)

this figure

The does not have any legend (it seems to be located outside of the plot limits). When I do something like

ax1.legend(frameon=False, prop={'size': 5}, loc='upper left') I get the message No artists with labels found to put in legend. How can I move the legend to within the subplot and customize it's appearance?

Leal answered 7/9, 2022 at 9:45 Comment(0)
S
6

Control over the legend position from within the Plot interface is still WIP but since you're using external matplotlib objects it's not that hard to transfer its contents:

f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)

(
    so.Plot(tips, x='total_bill', y='tip', color='day')
    .add(so.Dot(pointsize=2))
    .add(so.Line(color='k'), so.PolyFit(order=1), color=None)
    .on(ax1)
    .plot()
)

legend = f.legends.pop(0)
ax1.legend(legend.legend_handles, [t.get_text() for t in legend.texts])
Spiritualism answered 7/9, 2022 at 11:6 Comment(3)
This doesn't seem to work fully for the marker + colour legend in #75936369 - only the colour legend is accessible through the matplotlib handle.Feathers
The legend can be moved afterwards with the seaborn convenience function, move_legend: sns.move_legend(ax2, "center right")Wicked
See How to move marker and color sections of a figure legend for move marker + color legendWicked

© 2022 - 2024 — McMap. All rights reserved.