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

Seaborn relplot分面非共享轴时如何设置坐标轴为科学计数法

Seaborn分面图全子图配置科学计数法刻度

问题场景

使用seaborn 0.11.2绘制分面散点图,已关闭坐标轴共享,调用plt.ticklabel_format设置科学计数法时仅部分子图生效,初始实现代码:

titanic = sns.load_dataset('titanic')
g = sns.relplot(data=titanic, x='fare', y='age', col='sex', row='survived', height=2, facet_kws=dict(sharex=False, sharey=False))
g.set_titles(row_template='{row_name}', col_template='{col_name}')
plt.ticklabel_format(axis='both', style='scientific', scilimits=(0, 0))

初始运行效果:
示例效果图

失效原因

plt.ticklabel_format()属于matplotlib的pyplot顶层接口,默认仅对当前激活的单个子图生效。seaborn分面图绘制完成后,只有最后一个完成渲染的子图处于激活状态,因此仅该子图会应用刻度格式配置,其余开启独立坐标轴的子图不会被修改。

修复方案

遍历分面对象存储的所有子图轴实例,逐个配置科学计数法格式即可,完全兼容seaborn 0.11.x版本,修改后完整代码:

import seaborn as sns
import matplotlib.pyplot as plt

titanic = sns.load_dataset('titanic')
g = sns.relplot(
    data=titanic,
    x='fare',
    y='age',
    col='sex',
    row='survived',
    height=2,
    facet_kws=dict(sharex=False, sharey=False)
)
g.set_titles(row_template='{row_name}', col_template='{col_name}')

# 遍历所有子图坐标轴,逐轴设置科学计数法
for ax in g.axes.flat:
    ax.ticklabel_format(axis='both', style='scientific', scilimits=(0, 0))

plt.show()

说明:g.axes是存储所有子图轴对象的二维数组,使用flat属性可将其展开为一维迭代器,实现批量操作。如果需要单独调整指定位置子图的格式,可通过g.axes[行索引, 列索引]定位对应轴对象单独配置。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 06:57:28