pythonmatplotliblatexaxis-labelspgf

How do you include a bold symbol in the axis when exporting a pgf figure using matplotlib?


I am having trouble exporting a plot I made using matplotlib to a pgf. Without the bold symbol in the axis label, there is no issue, but with I get an error.

Here is my code:

import seaborn as sns
import numpy as np
import matplotlib as mpl
mpl.rcParams.update(mpl.rcParamsDefault)
mpl.use('pgf')
mpl.rcParams.update({
    'pgf.texsystem': "pdflatex",
    'font.family': 'serif',
    'text.usetex': True,
    'pgf.rcfonts': False,
    'font.serif': ["Computer Modern Roman"],
})
mpl.rc('text.latex', preamble=r'\usepackage{bm}')
import matplotlib.font_manager
import matplotlib.pyplot as plt

f, ax = plt.subplots(figsize = (8,4))
sns.set_color_codes("colorblind")
b = sns.barplot(x=probs, y=words, color='b')
ax.set(xlabel = r'{Probability of word, $p(w|\boldsymbol{\pi}_{ML})$}',
    ylabel = r'{Word, $w$}' )
b.set_yticklabels(labels=b.get_yticklabels(), va='center')
f.tight_layout()
plt.savefig('graph.pgf', format='pgf')

And the error I get is:

LatexError: LaTeX process halted
! Undefined control sequence.
<argument> ...rd, \(\displaystyle p(w|\boldsymbol 
                                                  {\pi }_{ML})\)}
<*> ...displaystyle p(w|\boldsymbol{\pi}_{ML})\)}}
                                                  
!  ==> Fatal error occurred, no output PDF file produced!
Transcript written on texput.log.

I thought including \usepackage{bm} in my preamble would've circumvented this issue?

Any help would be greatly appreciated!


Solution

  • For the second time this week...hours of trying to debug and searching has lead me to find the solution immediately after posting on stackoverflow.

    Solution:

    mpl.rcParams.update({
        'pgf.texsystem': "pdflatex",
        'font.family': 'serif',
        'text.usetex': True,
        'pgf.rcfonts': False,
        "pgf.preamble": "\n".join([
             r"\usepackage{bm}",
        ]),
        'font.serif': ["Computer Modern Roman"],
        'text.latex.preamble': pream,
    })