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

如何使Matplotlib轴标签中幂次字体与其余文本字体一致

解决Matplotlib中轴标签上下标与正文字体不一致的问题

问题根源在于:你用$...$包裹的数学表达式(比如$^2$)会触发Matplotlib的mathtext渲染,但默认mathtext的字体和你设置的cmr10没有绑定,导致上下标字体和正文脱节。

修复方案:统一mathtext与正文字体

修改你的Matplotlib配置,强制mathtext使用Computer Modern字体,和正文保持一致:

import matplotlib.pyplot as plt
import matplotlib as mpl

# 全局设置正文为Computer Modern serif字体
mpl.rcParams['font.family'] = 'serif'
mpl.rcParams['font.serif'] = ['Computer Modern Roman'] + mpl.rcParams['font.serif']

# 让mathtext使用和正文匹配的Computer Modern数学字体
mpl.rcParams['mathtext.fontset'] = 'cm'
mpl.rcParams['mathtext.rm'] = 'serif'

验证修改后的绘图代码

保持你的绘图逻辑不变,现在上下标字体就会和正文统一为Computer Modern:

fig, ax = plt.subplots()
ax.set_title('Results', fontsize=18)
ax.set_ylabel(r'Heat Flux (W/cm$^2$)', fontsize=18)
ax.set_xlabel('Wall Superheat (K)', fontsize=18)
ax.legend()
plt.show()

补充说明

  • mathtext.fontset = 'cm'会让matplotlib调用自带的Computer Modern数学字体,和cmr10(Computer Modern Roman)完全匹配;
  • 无需修改标签中的$^2$写法,保持原有的LaTeX式数学表达式即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 16:19:58