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

如何让Seaborn双对数散点图适配文本标签?

解决Seaborn双对数散点图文本标签被截断的问题

针对双对数轴下文本标签被图表边缘截断的问题,这里提供几个实用的解决方案:

方案1:手动调整对数轴极限

对数轴的刻度是指数级的,扩展轴极限时需要基于对数空间计算,而非线性数值。通过so.Log().limit()设置合适的上下限,给文本留出足够显示空间:

import seaborn as sns
import seaborn.objects as so
df = sns.load_dataset("penguins").sample(frac = 0.1)
df['island'] = 'long names here'
df['bill_length_mm'] = df['bill_length_mm'].apply(lambda x: 2.0**(x / 5))
df['bill_depth_mm'] = df['bill_depth_mm'].apply(lambda x: 2.0**((x - 10) / 2))

# 获取数据极值,基于对数比例扩展轴范围
x_min, x_max = df['bill_length_mm'].min(), df['bill_length_mm'].max()
y_min, y_max = df['bill_depth_mm'].min(), df['bill_depth_mm'].max()

(
   so.Plot(df, x='bill_length_mm', y='bill_depth_mm', text='island')
   .add(so.Dot()).add(so.Text(valign='bottom'))
   .scale(
       x=so.Log().limit(x_min/1.2, x_max*1.2),
       y=so.Log().limit(y_min/1.2, y_max*1.2)
   )
   .save('test_adjusted_limits.png')
)

方案2:调整文本偏移与对齐方式

给so.Text添加偏移量,让文本远离数据点,同时根据文本位置灵活调整对齐方式:

(
   so.Plot(df, x='bill_length_mm', y='bill_depth_mm', text='island')
   .add(so.Dot()).add(so.Text(valign='bottom', offset=8, halign='center'))
   .scale(x='log', y='log')
   .save('test_text_offset.png')
)
  • 若文本靠近右侧边缘,改为halign='left'
  • 若文本靠近左侧边缘,改为halign='right'

方案3:结合Matplotlib调整边距

利用Matplotlib底层API直接调整图表边距,确保文本完全显示:

import matplotlib.pyplot as plt

plot = (
   so.Plot(df, x='bill_length_mm', y='bill_depth_mm', text='island')
   .add(so.Dot()).add(so.Text(valign='bottom'))
   .scale(x='log', y='log')
)

# 渲染到Matplotlib轴并手动调整边距
fig, ax = plt.subplots()
plot.on(ax).plot()
plt.subplots_adjust(left=0.15, right=0.85, bottom=0.15, top=0.85)  # 按需调整数值
plt.savefig('test_margin_adjust.png')
plt.close()

方案4:使用自动布局优化

借助Matplotlib的tight_layout()自动适配所有元素:

import matplotlib.pyplot as plt

plot = (
   so.Plot(df, x='bill_length_mm', y='bill_depth_mm', text='island')
   .add(so.Dot()).add(so.Text(valign='bottom'))
   .scale(x='log', y='log')
)

fig, ax = plt.subplots()
plot.on(ax).plot()
plt.tight_layout()
plt.savefig('test_tight_layout.png')
plt.close()

内容的提问来源于stack exchange,提问作者Changed My Name Again

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 23:35:15