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

如何为Matplotlib配置LaTeX路径?开启usetex时遇文件未找到错误

如何为Matplotlib配置LaTeX路径以解决FileNotFoundError: [Errno 2] No such file or directory: 'latex'错误?

问题描述

我尝试用Matplotlib绘制包含LaTeX公式的图表,未启用text.usetex参数时示例代码能正常运行:

import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

但当设置plt.rcParams['text.usetex'] = True后,出现FileNotFoundError: [Errno 2] No such file or directory: 'latex'错误,请问该如何配置LaTeX路径解决这个问题?


解决方案

这个错误说明Matplotlib找不到系统中的LaTeX可执行文件,你可以通过以下两种方式配置路径:

1. 在代码中临时指定LaTeX路径(单次生效)

首先找到你安装的LaTeX可执行文件的完整路径:

  • Windows:如果是TeX Live,路径通常是C:\texlive\年份\bin\win32\latex.exe;如果是MiKTeX,路径类似C:\Program Files\MiKTeX\miktex\bin\x64\latex.exe
  • macOS:路径可能是/Library/TeX/texbin/latex或/usr/local/texlive/年份/bin/universal-darwin/latex
  • Linux:默认路径是/usr/bin/latex,自定义安装的话可能在/usr/local/texlive/年份/bin/x86_64-linux/latex

然后在代码中添加text.latex.command参数指定路径,示例如下(以Windows TeX Live为例):

import numpy as np
import matplotlib.pyplot as plt

# 指定LaTeX可执行文件的完整路径(用原始字符串避免转义问题)
plt.rcParams['text.latex.command'] = r'C:\texlive\2024\bin\win32\latex.exe'
plt.rcParams['text.usetex'] = True

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t,s)
plt.title(r'$\alpha_i > \beta_i$', fontsize=20)
plt.text(1, -0.6, r'$\sum_{i=0}^\infty x_i$', fontsize=20)
plt.text(0.6, 0.6, r'$\mathcal{A}\mathrm{sin}(2 \omega t)$', fontsize=20)
plt.xlabel('time (s)')
plt.ylabel('volts (mV)')
plt.show()

2. 修改Matplotlib配置文件(永久生效)

如果不想每次写代码都指定路径,可以修改Matplotlib的全局配置文件:

  • 首先运行以下代码找到配置文件的位置:
    import matplotlib
    print(matplotlib.matplotlib_fname())
    
  • 打开输出的配置文件,找到#text.latex.command : latex这一行,去掉开头的注释符#,将后面的latex替换为你的LaTeX可执行文件完整路径,比如:
    text.latex.command : C:\texlive\2024\bin\win32\latex.exe
    
  • 保存配置文件后,重启Python环境即可生效。

额外检查项

  • 确保你安装的LaTeX是完整版本(比如TeX Live选择Full安装),至少包含amsmath、amsfonts等常用公式包,否则可能出现其他LaTeX编译错误。
  • 也可以尝试将LaTeX的bin目录添加到系统环境变量PATH中,这样Matplotlib就能自动找到latex命令,无需手动指定路径。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:53:14