Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sans-serif math with latex in matplotlib

The following script:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as mpl

mpl.rc('font', family='sans-serif')
mpl.rc('text', usetex=True)

fig = mpl.figure()
ax = fig.add_subplot(1,1,1)
ax.text(0.2,0.5,r"Math font: $451^\circ$")
ax.text(0.2,0.7,r"Normal font (except for degree symbol): 451$^\circ$")

fig.savefig('test.png')

is an attempt to use a sans-serif font in matplotlib with LaTeX. The issue is that the math font is still a serif font (as indicated by the axis numbers, and as demonstrated by the labels in the center). Is there a way to set the math font to also be sans-serif?

like image 551
astrofrog Avatar asked Mar 29 '10 12:03

astrofrog


People also ask

Is LaTeX a sans serif?

The default LaTeX font Computer Modern has serifs. The following commands can be used to change to a font without serifs (sans serif) and vice-versa (serif/roman).

How do I change the font in Matplotlib?

Create a figure and a set of subplots. Plot x data points using plot() method. To change the font size of the scale in matplotlib, we can use labelsize in the ticks_params()method. To display the figure, use show() method.


3 Answers

I always have text.usetex = True in my matplotlibrc file. In addition to that, I use this as well:

mpl.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!
]  

Hope that helps.

like image 182
Paul H Avatar answered Oct 04 '22 09:10

Paul H


The easiest way is to use matplotlib's internal TeX, e.g.:

import pylab as plt
params = {'text.usetex': False, 'mathtext.fontset': 'stixsans'}
plt.rcParams.update(params)

If you use an external LaTeX, you can use, e.g., CM Bright fonts:

params = {'text.usetex': True, 
          'text.latex.preamble': [r'\usepackage{cmbright}', r'\usepackage{amsmath}']}
plt.rcParams.update(params)

Note, that the CM Bright font is non-scalable, and you'll not be able to save PDF/PS! Same with other options with external LaTeX I've found so far.

like image 39
Vyacheslav Avatar answered Oct 04 '22 09:10

Vyacheslav


This will enable you to use the Computer Modern Sans font if you, as I, prefer it over Helvetica:

mpl.rcParams['text.usetex'] = True 
mpl.rcParams['text.latex.preamble'] = [r'\usepackage[cm]{sfmath}']
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'cm'
like image 45
nedim Avatar answered Oct 04 '22 08:10

nedim