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

Matplotlib中坐标轴标签公式内字体无法切换为Times New Roman的问题

解决Matplotlib公式字体不随全局设置改变的问题
  • 问题根源:用$...$包裹的公式是通过LaTeX引擎渲染的,单独设置plt.rcParams["font.family"]只会影响普通文本,LaTeX渲染的内容有独立的字体配置逻辑。

  • 具体解决办法:

    1. 先确认系统已安装Times New Roman对应的LaTeX字体包(比如newtxtext/newtxmath或txfonts)
    2. 配置Matplotlib的LaTeX渲染参数,让公式部分也使用Times New Roman:
      import matplotlib.pyplot as plt
      
      # 全局字体设置
      plt.rcParams["font.family"] = "Times New Roman"
      # 启用LaTeX渲染并指定字体包
      plt.rcParams["text.usetex"] = True
      plt.rcParams["text.latex.preamble"] = r"\usepackage{newtxtext,newtxmath}"
      
      # 绘图测试
      plt.figure(figsize=(8,5))
      plt.xlabel("Stromdichte A cm$^{-2 test}$", fontsize=40)
      plt.show()
      
    3. 若不想全局开启LaTeX渲染,也可以在单个标签里直接指定字体:
      plt.xlabel(r"\fontfamily{ptm}\selectfont Stromdichte A cm$^{-2 test}$", fontsize=40)
      
      其中ptm是Times New Roman在LaTeX中的字体家族标识。
  • 补充说明:开启text.usetex=True后,Matplotlib会调用系统LaTeX引擎处理所有文本,此时全局font.family设置会被LaTeX配置覆盖,务必确保预amble里的字体包正确加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 11:42:34