在Matplotlib/Python中使用siunitx包出现错误的求助
解决Matplotlib中结合siunitx与预定义mplstyle的报错问题
核心排查与解决步骤
检查样式与pgf后端的配置冲突
预定义的mplstyle中如果已经设置了text.usetex=True,切换到pgf后端时需保证LaTeX配置统一。重点确保字体设置匹配:mplstyle里的font.family要和pgf预编译代码中的LaTeX字体命令一致,否则会触发LaTeX编译错误。可以在代码中显式覆盖冲突参数:import matplotlib.pyplot as plt plt.style.use('你的样式文件.mplstyle') # 切换pgf后端并配置siunitx plt.switch_backend('pgf') plt.rcParams.update({ "pgf.texsystem": "pdflatex", "text.usetex": True, "pgf.preamble": [ r"\usepackage{siunitx}", r"\sisetup{detect-all}", # 自动匹配matplotlib字体 # 补充mplstyle对应的LaTeX字体命令,例如用Times New Roman: # r"\usepackage{times}" ] })验证系统LaTeX环境的siunitx包
报错可能源于LaTeX环境未安装siunitx。手动创建测试文件test.tex:\documentclass{article} \usepackage{siunitx} \begin{document} \SI{10}{\meter} \end{document}运行
pdflatex test.tex,若报错则通过TeX Live/MikTeX的包管理器安装siunitx。严格控制后端切换时机
必须在创建任何绘图对象(如fig, ax)之前切换pgf后端并更新配置,否则会因上下文初始化冲突报错。正确顺序:import matplotlib.pyplot as plt # 1. 加载预定义样式 plt.style.use('你的样式文件.mplstyle') # 2. 切换后端并配置siunitx plt.switch_backend('pgf') plt.rcParams.update({"pgf.preamble": [r"\usepackage{siunitx}", r"\sisetup{detect-all}"]}) # 3. 创建绘图 fig, ax = plt.subplots() ax.set_xlabel(r"\SI{5}{\kilo\hertz}") plt.savefig('output.pdf')合并样式中的LaTeX预设置
若mplstyle中已有text.latex.preamble配置,需将其中的包命令合并到pgf.preamble中,避免重复加载或冲突。例如样式里有text.latex.preamble: \usepackage{amsmath},则pgf配置中也要保留该命令。
完整可运行示例
import matplotlib.pyplot as plt # 加载自定义报告样式 plt.style.use('report_style.mplstyle') # 切换pgf后端并配置siunitx plt.switch_backend('pgf') plt.rcParams.update({ "pgf.texsystem": "pdflatex", "text.usetex": True, "pgf.preamble": [ r"\usepackage{siunitx}", r"\sisetup{detect-all}", # 匹配样式中的无衬线字体 r"\usepackage{helvet}", r"\renewcommand{\familydefault}{\sfdefault}" ] }) # 生成带siunitx的图表 fig, ax = plt.subplots(figsize=(6, 4)) ax.plot([1, 2, 3], [10, 20, 15]) ax.set_title(r"信号强度随频率变化") ax.set_xlabel(r"频率 (\SI{10}{\kilo\hertz})") ax.set_ylabel(r"强度 (\SI{5}{\decibel})") # 保存为pgf(用于LaTeX嵌入)和pdf plt.savefig('signal_plot.pgf', bbox_inches='tight') plt.savefig('signal_plot.pdf', bbox_inches='tight') plt.close()
内容的提问来源于stack exchange,提问作者MrT77
相关产品推荐
相关产品推荐

