You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Seaborn 0.12 Objects自定义子图中的图例?

解决Seaborn Objects模块子图图例定制问题

直接通过Seaborn Objects自身的.legend()方法配置图例即可,无需调用Matplotlib原生的ax.legend()——因为Objects模块的绘图元素不会自动给轴对象添加带标签的艺术家,导致原生方法找不到图例源。

修改后的完整代码:

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-HT modulation')
     # 自定义图例:指定位置、关闭边框、设置字体大小
     .legend(loc='upper left', frameon=False, fontsize=5)
     .on(ax1)
     .plot()
)
plt.tight_layout()
sns.despine(trim=True)

关键说明

  • .legend()方法支持传递所有Matplotlib Legend类的参数,比如loc控制位置、frameon关闭边框、fontsize调整字体大小;
  • 如果需要更精细的定制(比如修改图例标题、标记缩放比例),可以结合so.Legend对象,示例:
    .legend(so.Legend(title="Modulation Type", markerscale=0.7), loc='upper left', frameon=False, fontsize=5)
    
  • 代码中PolyFit的color=None会让这条拟合线不显示在图例中,仅保留Dot按sig_modulation分组的图例项。

内容的提问来源于stack exchange,提问作者GTMeijer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 01:15:54