python - 在 LateX 中编译时使用 matplotlib+pgf 后端获取半透明文本
问题描述
所以我使用pgf backend
in 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)
文本看起来没有变化,如果我尝试通过使用\textcolor
xcolor 包(或 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 样式怎么办......
解决方案
感谢@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)
推荐阅读
- java - ContainsValue 与 equals 方法 TreeMap
- reactjs - 在 React 的 render 方法之外进行计算的最佳位置在哪里?
- c# - 使用 certenroll 创建证书时的 CRYPT_E_UNEXPECTED_MSG_TYPE
- javascript - vue nuxt js - 组件级缓存不起作用
- python - 哪些参数会影响 SVM 中超平面的位置以及如何影响?
- list - 如何查找和替换多个文本文件?
- javascript - 调用函数时如何解决promise?p5.js
- python - 使用python在mysql查询中插入错误
- r - R:根据小时和天填写缺失值
- node.js - 原生节点 esm 的 vue-test-utils 问题:TypeError: mount is not a function