I'm writing a LaTeX document and I include some matplotlib plots in it, in .pgf format with \include{file.pgf}. It has advantages over exporting the matplotlib plot to .pdf or .eps formats in that the fonts matches the one of my document and probably other advantages, but that is beside the main question.
In my LaTeX document I use the siunitx package, and I'd like to use it for the matplotlib plots too. For instance some axis might be the distance in meters, so I'd like to use Distance (\si{\meter}) instead of Distance (m).
From what I gathered from an extensive Google research, in the Python file .py, I came up with the following example:
import matplotlib as mpl
mpl.use('pgf')
mplparams = {"pgf.rcfonts": False}
mpl.rc('text', usetex=True)
mpl.rcParams.update(mplparams)
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
if "siunitx" not in plt.rcParams["text.latex.preamble"]:
plt.rcParams["text.latex.preamble"].append(r"\usepackage{siunitx}")
X = [0, 1, 2, 3, 4, 5]
Y = [-2, 7 , 3 , 8 , 7, 5]
plt.plot(X, Y)
plt.xlabel('Distance (\si{\meter})')
plt.savefig('file.pgf')
However it won't work and yields the error message:
File "(...)\Anaconda3\lib\site-packages\matplotlib\backends\backend_pgf.py", line 375, in get_width_height_descent
raise ValueError(msg % (text, e.latex_output))
ValueError: Error processing 'Distance (\si{\meter})'
LaTeX Output:
! Undefined control sequence.
<argument> ...12.000000}\selectfont Distance (\si
{\meter })
<*> ....000000}\selectfont Distance (\si{\meter})}
No pages of output.
Transcript written on texput.log.
If I replace \si{\meter} by m, it does work.
I am therefore unable to use the siunitx package within Python. How could I make it work?
rcParamsthis way only changes this for the current Python run; and you can make another call to thercParamsto undo the changes later, if that's an issue. You don't have to alter your global parameters. (and if you're using.updateyou don't have to include all these parameters to change the few values you actually want to change). – Skillmon Aug 31 '22 at 11:47