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

如何在seaborn图表标题中为带下划线的字符串设置斜体

问题说明

需求是为seaborn绘制的countplot图表设置标题,格式为:countplot of adult_male by alive,其中字段名adult_male、alive需要显示为斜体。
之前尝试用$符号包裹文本实现斜体,但被包裹字符串包含下划线时方法失效,测试代码如下:

titanic = sns.load_dataset('titanic')

feature = "adult_male"
hue = "alive"

ax = sns.countplot(data=titanic, x=feature);
ax.set_title(f"countplot of ${feature}$ by ${hue}$");

运行后下划线会被解析为数学公式下标,无法得到预期斜体效果。

失效原因

$是matplotlib内置mathtext模式的触发标记,被$包裹的内容会按照LaTeX数学公式语法解析:

  • 下划线_在数学公式语法中是下标特殊标记,不会作为普通下划线字符显示
  • 数学模式默认的斜体是为数学变量设计的,字符间距和普通文本斜体有区别
修正方案

方案1:转义特殊字符+mathtext斜体(代码改动最小)

对字段名中的下划线做转义处理(LaTeX语法中普通下划线需要写为\_),同时用\mathit{}包裹字段名,保证显示为普通文本斜体而非数学变量斜体,只需要在原有代码基础上做少量修改即可:

import seaborn as sns
import matplotlib.pyplot as plt

titanic = sns.load_dataset('titanic')
feature = "adult_male"
hue = "alive"

ax = sns.countplot(data=titanic, x=feature)
# 转义下划线,避免被解析为下标
escaped_feature = feature.replace("_", r"\_")
escaped_hue = hue.replace("_", r"\_")
ax.set_title(f"countplot of $\mathit{{{escaped_feature}}}$ by $\mathit{{{escaped_hue}}}$")
plt.show()

方案2:分段设置文本样式(无需处理特殊字符,通用性更强)

不使用mathtext模式,将标题拆分为多段文本块,给需要斜体的部分单独指定fontstyle='italic'属性,不需要转义任何特殊字符,即使字段名包含下划线、百分号等特殊符号也能正常显示,适合批量处理不同字段的场景:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredOffsetbox, TextArea, HPacker

titanic = sns.load_dataset('titanic')
feature = "adult_male"
hue = "alive"

ax = sns.countplot(data=titanic, x=feature)
# 构建不同样式的文本块
text1 = TextArea("countplot of ")
text2 = TextArea(f"{feature}", textprops={'fontstyle':'italic'})
text3 = TextArea(" by ")
text4 = TextArea(f"{hue}", textprops={'fontstyle':'italic'})
# 横向拼接所有文本块
title_box = HPacker(children=[text1, text2, text3, text4], align="center", pad=0, sep=2)
# 将拼接好的标题放到图表顶部居中位置
anchored_title = AnchoredOffsetbox(loc='upper center', child=title_box, frameon=False,
                                  bbox_to_anchor=(0.5, 1.02), 
                                  bbox_transform=ax.transAxes, borderpad=0)
ax.add_artist(anchored_title)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 20:27:26