How can I customize the legend with Seaborn 0.12 objects?

Viewed 49

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)

Produces this figure which 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?

1 Answers

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.legendHandles, [t.get_text() for t in legend.texts])
Related