问题
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