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

绘制Sympy矩阵时触发ParseSyntaxException错误求助

解决Matplotlib图例中Sympy矩阵LaTeX标签的ParseSyntaxException错误

问题根源

Sympy生成的矩阵LaTeX代码依赖amsmath包的bmatrix环境,但Matplotlib默认使用的mathtext渲染引擎不支持这类完整LaTeX环境,仅能解析基础数学命令,因此触发语法解析错误。

两种可行解决方案

方案1:启用Matplotlib的系统LaTeX渲染

如果你的系统已安装LaTeX环境(如TeX Live、MiKTeX),可以配置Matplotlib调用系统LaTeX渲染,完美支持所有LaTeX语法:

from sympy import Matrix, latex
import matplotlib.pyplot as plt

# 开启LaTeX渲染配置
plt.rcParams.update({
    "text.usetex": True,
    "font.family": "serif",
})

a = Matrix([1, 2])
plt.plot([0, 0], label=fr"${latex(a)}$")
plt.legend()
plt.show()

方案2:适配Mathtext的手动格式转换

若没有LaTeX环境,可将Sympy输出的bmatrix语法替换为mathtext兼容的格式。比如把\begin{bmatrix}1\\2\end{bmatrix}转换为\left[\begin{array}{c}1\\2\end{array}\right]:

from sympy import Matrix, latex
import matplotlib.pyplot as plt

a = Matrix([1, 2])
# 替换bmatrix为mathtext支持的array环境
mathtext_compatible = latex(a).replace("bmatrix", "array}{c")
label = f"$\\left[{mathtext_compatible}\\right]$"

plt.plot([0, 0], label=label)
plt.legend()
plt.show()

也可以直接构造兼容的向量标签:

# 直接生成mathtext支持的列向量
label = f"$\\left[\\begin{{array}}{{c}} {a[0]} \\\\ {a[1]} \\end{{array}}\\right]$"
plt.plot([0, 0], label=label)
plt.legend()
plt.show()

额外提示

  • Matplotlib的mathtext仅支持有限的LaTeX命令,复杂环境需依赖系统LaTeX渲染。
  • 启用text.usetex=True后,文本渲染速度会略有下降,但字体风格更统一规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 14:06:06