如何使用Seaborn 0.12对象自定义图例?

4
新的 Seaborn 对象(v 0.12)非常好,但我很难处理图例自定义。特别是在使用 matplotlib 定义子图时。我的代码:
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

图例似乎位于绘图范围之外。当我执行以下操作时:

ax1.legend(frameon=False, prop={'size': 5}, loc='upper left') 我会收到消息 No artists with labels found to put in legend. 如何将图例移动到子图内并自定义其外观?

1个回答

3

虽然在绘图界面内部控制图例位置仍处于WIP状态,但由于您正在使用外部的matplotlib对象,因此传输其内容并不那么困难:

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])

1
这似乎对 https://dev59.com/JV7Rs4gBPY-HTNNjhqic 中的标记器和颜色图例并不完全适用 - 只有颜色图例可以通过 matplotlib 句柄访问。 - some3128
1
传说可以在之后使用seaborn的便利函数move_legend来移动:sns.move_legend(ax2, "center right") - Joshua Shew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接