TAGS :Viewed: 16 - Published at: a few seconds ago

[ Matplotlib: different font type rendering in axis labels ]

Using the code below I get a label that with two different font types. 'Surface Area' is in sans-serif, while the Angstrom and the superscript are serif. Is there anyway I can make the entire y-label sans-serif?

Thanks in advance!

import matplotlib.pylab as plt
import random

random.seed(20)
data = [random.random() for i in range(10)]

fig, ax = plt.subplots()
ax.plot(data)
ax.set_ylabel(r'Surface Area ($\AA^2$)', size =16)

plt.show()

Surface Area

Answer 1


A quick and dirty way in matplotlib version 1.3.0 and up, you can use Latex \textup and \textbf:

ax.set_ylabel('\textup{Surface Area} (\AA^2)', size =16)

see tutorials here: http://matplotlib.org/users/usetex.html, don't forget to enable latex by:

rc('text', usetex=True)

This should work for older versions as well as long as you have Latex installed. But if you want to stick to matplotlib's mathtext, it can be done as well:

>>> matplotlib.rcParams['mathtext.fontset']='stixsans'
>>> for i in [1]:
    fig, ax = plt.subplots()
    ax.plot(data)
    ytx=ax.set_ylabel(r'Surface Area $(\AA^2)$', size =16)

Not every font will work with mathtext, stixsans is the one that will 'look like' sans-serif: http://matplotlib.org/users/mathtext.html#mathtext-tutorial. Honestly, the difference is very small. I am pretty sure Angstrom is not in stixsans so to render it mathtext falls back to the default Computer Modern font.

enter image description here