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

Matplotlib中使用LaTeX align*环境报错:Environment align* undefined

在Matplotlib中使用align*环境时遭遇LaTeX错误

我尝试在Matplotlib中使用align*环境,却触发如下LaTeX错误:

! LaTeX Error: Environment align undefined.

See the LaTeX manual or LaTeX Companion for explanation.
Type H for immediate help.
...

我猜测问题出在amsmath包的配置上,但不确定具体原因。我的设备是Windows系统,已安装MikTeX,完整代码如下:

import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
from decimal import Decimal
import matplotlib as mpl

mpl.rc('text', usetex = True)
mpl.rc('font', **{'family' : "sans-serif"})
params= {'text.latex.preamble' : [r'\usepackage{amsmath}']}
plt.rcParams.update(params)

def lorentz(x, *p):
    y0, xc, w, A = p
    return y0 + (2*A/np.pi) * (w/(4*(x-xc)**2+w**2))

freq = [19.050500, 19.095500, 19.140500, 19.185500, 19.230500, 19.275500, 19.320500, 19.365500, 19.410500, 19.455500, 19.465500, 19.475500, 19.485500, 19.495500, 19.505500, 19.515500, 19.525500, 19.535500, 19.545500, 19.590500, 19.630500, 19.680500, 19.725500, 19.770500, 19.815500, 19.860500, 19.905500, 19.950500]
U = [40, 40, 56, 56, 64, 72, 96, 120, 176, 304, 352, 400, 432, 432, 400, 352, 304, 264, 232, 144, 104, 80, 72, 64, 56, 48, 40, 40]

U_squared = [(item*1e-3)**2 for item in U]

p0 = [2.5e-5, 19.489, 0.0295, 8.3e-4]
coeff, pcov = curve_fit(lorentz, freq, U_squared, p0=p0)

std_err = np.sqrt(np.diag(pcov))

freq_steps = np.linspace(min(freq), max(freq), 1000)

fit = lorentz(freq_steps, *coeff)

fig, ax = plt.subplots()

plt.xlabel(r"$f \, \left[ \mathrm{MHz} \right]$")
plt.ylabel(r"$U^2 \, \left[ \mathrm{V^2} \right]$ ")

data_plot, = plt.plot(freq, U_squared, linestyle="None", marker=".")
fit_plot, = plt.plot(freq_steps, fit, linestyle="--", color="tab:red")

plt.legend([data_plot, fit_plot],["measured data", "Lorentz fit"])

props = dict(boxstyle='square', facecolor='none', edgecolor='black')

plt.text(0.02, 0.95, r"\begin{align*} U^2 (f) &= y_0 + \frac{2A}{\pi} \frac{w}{4(f-f_0)^2+w^2} \\ " +
         r"y_0 &= \," + "{:.2e}".format(Decimal(coeff[0])) + "\, \pm \," + "{:.2e}".format(Decimal(std_err[0]))
         + r"\\ f_0 &= \," + str(np.round(coeff[1], 2)) + "\, \pm \," + "{:.2e}".format(Decimal(std_err[1]))
         + r"\\ w &= \," + "{:.2e}".format(Decimal(coeff[2])) + "\, \pm \," + "{:.2e}".format(Decimal(std_err[2]))
         + r"\\ A &= \," + "{:.2e}".format(Decimal(coeff[3])) + "\, \pm \," + "{:.2e}".format(Decimal(std_err[3])) + r"\end{align*}",
         transform=ax.transAxes, bbox=props, ha='left')

plt.show()

恳请各位提供帮助!

内容的提问来源于stack exchange,提问作者Luca-Amadeus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:30:52