3
votes

I'm trying to achieve sans-serif axes labels and ticks in matplotlib with pgf. I want to control that by rcParams so I have it working for all subsequent plots. Currently, I'm using

"pgf.rcfonts":False,
"pgf.texsystem": "pdflatex",   
"text.usetex": True,                
"font.family": "sans-serif",

which I adapted from the mpl docs. It does set all my text in the figure to sans-serif. However, the numbers are kept with a serif font. I want them to be sans-serif. As soon as i force the formatter, its sans-serif. Any way to get it to do that automatically? MinEx follows...

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

#define style
style = {
        "pgf.rcfonts":False,
        "pgf.texsystem": "pdflatex",   
        "text.usetex": True,                
        "font.family": "sans-serif"
        }
#set
mpl.rcParams.update(style)

#get data
data = np.random.random(100)
#set up plot
f,ax = plt.subplots()
ax.plot(data)
#label something
ax.set_xlabel('Runner')

The label is sans now. The ticks are not! But when calling

ax.xaxis.set_major_formatter(FormatStrFormatter('%d'))

they are.

2
This also is a problem for legends. I traced it down to pgf. If I add the sansmath package in mpl.rc it does work in mpl. However, looking at the pgf, its not forced for number. Labels are getting the \sffamily in front, numbers are directly parsed and thus dont get that.Max
Ok if I use ne manual way, another problem arises. It does parse the numbers in sans-serif to my tex doc, but FormatStrFormatter resets the locale to US while I need GermanMax

2 Answers

1
votes

According to the pgf texsystem example, you need to use the "pfg" backend (mpl.use("pgf")) and choose the font you want to use:

style = {
        "pgf.texsystem": "pdflatex",   
        "text.usetex": True,                
        "pgf.preamble": [
         r"\usepackage[utf8x]{inputenc}",
         r"\usepackage[T1]{fontenc}",
         r"\usepackage{cmbright}",
         ]
        }

enter image description here

Alternatively you may use a formatter, which does not format the ticklabels as latex math (i.e. does not put them into dollar signs).

One may adapt the default ScalarFormatter not to use latex math by setting

ax.xaxis.get_major_formatter()._usetex = False
ax.yaxis.get_major_formatter()._usetex = False
0
votes

The problem is LateX related. You just need to load the extra cmbright package that enable sans-serif math fonts.

On Debian-like systems:

sudo apt install texlive-fonts-extra

On Fedora:

sudo dnf install texlive-cmbright

Then try your code with this style:

style = {   
        "text.usetex": True,                
        "font.family": "sans-serif"
        "text.latex.preamble" : r"\usepackage{cmbright}"
        }