How to avoid calling latex in matplotlib (output to pgf)

隐身守侯 提交于 2020-03-02 03:53:46

问题


I'm using matplotlib with its pgf backend to generate plots that I include in my LaTeX beamer document. I run into trouble when I use latex commands that are not defined. But for my application, I don't need matplotlib to generate the labels or annotations with latex, I only want a correct pgf output and I will call LaTeX on my beamer document. If I would run this code in a notebook, I would expect just to have a plot with a literal "\si{\percent}" in the xlabel.

In the MWE below, when I run it with the commented line (using \si{\percent}), matplotlib crashes with a latex error ('unknown command si'). I don't want to create a preamble with matplotlib, I just want the pgf output containing the \si{\percent} command...

If I use double backslashes, the code passes but the double backslash appears also in the pfg output and hence latex doesn't recognize the command (it sees a newline, I guess).

I don't understand the "value" of the plt.rc('text', usetex=False). I thought this would disable calling LaTeX alltogether...

import numpy as np
import matplotlib as mpl
mpl.use('pgf')
from matplotlib import pyplot as plt
from matplotlib import rc
plt.style.use('bmh')
plt.rc('pgf',rcfonts=False)
plt.rc('text', usetex=False)
x = np.linspace(0,100,101)
y = np.cos(x/100)*np.exp(-x/100)
plt.plot(x,y)
#plt.xlabel(r'value (\si{\percent})')
plt.xlabel(r'value (%)')
plt.savefig('test.pgf')

回答1:


Is there any reason why you're hesitant to include a preamble? Doing so makes for an easy solution. The following works for me:

import numpy as np
import matplotlib as mpl

mpl.use('pgf')

from matplotlib import pyplot as plt

pgf_with_latex = {
        'text.usetex': False,
        'pgf.rcfonts': False,
        "pgf.preamble": [
                r"\usepackage{siunitx}"
                ]
}

mpl.rcParams.update(pgf_with_latex)

plt.style.use('bmh')

x = np.linspace(0,100,101)
y = np.cos(x/100)*np.exp(-x/100)
plt.plot(x,y)

plt.xlabel(r'value (\si{\percent})')
plt.savefig('test.pgf')


来源:https://stackoverflow.com/questions/54593261/how-to-avoid-calling-latex-in-matplotlib-output-to-pgf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!