5

I'm trying to use Latex with matplotlib for the first time. It seems that when using Latex matplotlib uses a serif font for the axes labels. I tried explicitly setting the font-family to 'sans-serif' using

rc('font',family='sans-serif')

but this had no effect, I'm assuming this is because the axes-labels are inside a math-environment. Is there a way to set the 'rc' so that matplotlib will use a sans-serif font for the axes labels?

Thanks!

1 Answer 1

12

Sans-serif math fonts can be used in LaTeX with the help of the sfmath package. To use this package in matplotlib, you need to alter the LaTeX preamble it uses to compile text, which can be done through the 'text.latex.preamble' rc option. Hence,

rc('text.latex', preamble='\usepackage{sfmath}')

should do what you want. You can also choose another font and supply it as an option to the package, see sfmath's documentation for reference.

2
  • 3
    Works great! However, my ipython complained about a unicode escape character being used ('\u'). My solution is tom mahe it a raw string: rc('text.latex', preamble=r'\usepackage{sfmath}')
    – trueter
    May 6, 2017 at 14:25
  • Very nice. I was searching all over matplotlib docs and here for almost one hour w/o success. But this works like a charm! +1
    – Walter
    Feb 29 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.