pythonstringmatplotliblatex

Matplotlib LaTeX preamble not correctly interpreted


I was trying to use a custom LaTeX preamble with matplotlib, but it raises

ValueError: Key text.latex.preamble: Could not convert ['\\usepackage{siunitx}' ...] to str

For some reason, the \ are converted into \\, but I don't understand why. I'm using Python v. 3.11.5 and Matplotlib v. 3.7.2.

Here is the MWE (inspired from this post):

import matplotlib.pyplot as plt
from matplotlib import rcParams


rcParams['text.usetex'] = True
rcParams['text.latex.preamble'] = [
       r'\usepackage{siunitx}',   # i need upright \micro symbols, but you need...
       r'\sisetup{detect-all}',   # ...this to force siunitx to actually use your fonts
       r'\usepackage{helvet}',    # set the normal font here
       r'\usepackage{sansmath}',  # load up the sansmath so that math -> helvet
       r'\sansmath'               # <- tricky! -- gotta actually tell tex to use!
]

fig, ax = plt.subplots()
fig.show()

Solution

  • enter image description here

    rcParams expects a string. Below I've joined the elements of your list of strings using newlines.

    import matplotlib.pyplot as plt
    from matplotlib import rcParams
    
    rcParams['text.usetex'] = True
    rcParams['text.latex.preamble'] = '\n'.join([
           r'\usepackage{siunitx}',   # i need upright \micro symbols, but you need...
           r'\sisetup{detect-all}',   # ...this to force siunitx to actually use your fonts
    ])
    
    fig, ax = plt.subplots()
    plt.xlabel(r'$a=\SI{12}{\kg}$')
    fig.show()
    

    Note that \kg is a macro defined by SIUnitx.


    PS, I have omitted a few packages that I have not installed.