首页 > 解决方案 > 在 LateX 中编译时使用 matplotlib+pgf 后端获取半透明文本

问题描述

所以我使用pgf backendin matplotlib 在我的 TeX 文档中包含一些自动编译的对我的 Tex 文档的其他部分(图形、参考书目)的引用。

import matplotlib
matplotlib.use('pgf')

import matplotlib.pyplot as plt
plt.figure()
plt.txt(0.0,0.5,r'Some text compiled in latex \cite{my_bib_tag}')
plt.savefig("myfig.pgf", bbox_inches="tight", pad_inches=0)

然后在我的 tex 文档中,我有以下几行:

\usepackage[dvipsnames]{xcolor}
%yada yada yada 
\begin{figure}
\input{myfig.pgf}
\end{figure}

它工作得很好,但是当我尝试为文本添加一些透明度时它不起作用。例如设置时:

plt.txt(0.0,0.5,r'Some text compiled in latex \cite{my_bib_tag}', alpha=0.5)

文本看起来没有变化,如果我尝试通过使用\textcolorxcolor 包(或 LateX 中的任何其他命令,如透明包)在编译中执行此操作,我在编译 Python 时会遇到解析错误。

我尝试转义字符,但不知何故我无法让它工作。

plt.txt(0.0,0.5,r'\textcolor{gray}{Some text compiled in latex \cite{my_bib_tag}}', alpha=0.5)
#raise ValueError !Undefined Control Sequence

编辑 1:我尝试在序言中添加所需的包,但在保存到 pgf(使用 pgf 后端)时它不起作用,它使用 Agg 后端工作(我认为这是预期的行为)。但是我需要将它保存在 pgf 中才能动态解析引用。

import matplotlib

import matplotlib.pyplot as plt
matplotlib.rcParams["text.usetex"] = True
matplotlib.rcParams["text.latex.preamble"].append(r'\usepackage[dvipsnames]{xcolor}')
matplotlib.verbose.level = 'debug-annoying'

plt.figure()
plt.text(0.0,0.5,r'\textcolor{gray}{Some text compiled in latex \cite{my_bib_tag}}', alpha=0.5)
#works in .png, does not work in .pgf
#plt.savefig("myfig.png", bbox_inches="tight", pad_inches=0)

编辑 2:解决方法是使用 plt.text 中的颜色参数,但如果我想使用更复杂的 LateX 样式怎么办......

标签: pythonmatplotliblatexpgf

解决方案


感谢@ImportanceOfBeingErnest,我终于使它与 pgf 后端一起工作:

import matplotlib
matplotlib.use('pgf')

import matplotlib.pyplot as plt

pgf_with_custom_preamble = {
    "text.usetex": True,    # use inline math for ticks
    "pgf.rcfonts": False,   # don't setup fonts from rc parameters
    "pgf.preamble": [
                     "\\usepackage[dvipsnames]{xcolor}",         # load additional packages
                     ]
}
matplotlib.rcParams.update(pgf_with_custom_preamble)

plt.figure()
plt.text(0.0,0.5,r'\textcolor{gray}{Some text compiled in latex \cite{my_biblio_tag}}')
plt.savefig("myfig.pgf", bbox_inches="tight", pad_inches=0)

推荐阅读