4

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?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
GTMeijer
  • 41
  • 1

1 Answers1

4

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])
Joshua Shew
  • 618
  • 2
  • 19
mwaskom
  • 46,693
  • 16
  • 125
  • 127
  • This doesn't seem to work fully for the marker + colour legend in https://stackoverflow.com/questions/75935869/how-to-move-marker-and-color-sections-of-a-figure-legend - only the colour legend is accessible through the `matplotlib` handle. – some3128 Jul 27 '23 at 18:08
  • The legend can be moved afterwards with the `seaborn` convenience function, `move_legend`: `sns.move_legend(ax2, "center right")` – Joshua Shew Aug 05 '23 at 08:20