How to change fonts in matplotlib (python)?

Posted on

Question :

How to change fonts in matplotlib (python)?

It sounds as an easy problem but I do not find any effective solution to change the font (not the font size) in a plot made with matplotlib in python.

I found a couple of tutorials to change the default font of matplotlib by modifying some files in the folders where matplotlib stores its default font – see this blog post – but I am looking for a less radical solution since I would like to use more than one font in my plot (text, label, axis label, etc).

Asked By: SirC


Answer #1:

Say you want Comic Sans for the title and Helvetica for the x label.

csfont = {'fontname':'Comic Sans MS'}
hfont = {'fontname':'Helvetica'}

plt.xlabel('xlabel', **hfont)
Answered By: aidnani8

Answer #2:

You can also use rcParams to change the font family globally.

 import matplotlib.pyplot as plt
 plt.rcParams[""] = "cursive"
 # This will change to your computer's default cursive font

The list of matplotlib’s font family arguments is here.

Answered By: morepenguins

Answer #3:

I prefer to employ:

from matplotlib import rc
rc('text', usetex=True)
Answered By: guhur

Answer #4:

import pylab as plb
plb.rcParams['font.size'] = 12


import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12
Answered By: nagordon

Answer #5:

The Helvetica font does not come included with Windows, so to use it you must download it as a .ttf file.
Then you can refer matplotlib to it like this (replace “crm10.ttf” with your file):

import os
from matplotlib import font_manager as fm, rcParams
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

fpath = os.path.join(rcParams["datapath"], "fonts/ttf/cmr10.ttf")
prop = fm.FontProperties(fname=fpath)
fname = os.path.split(fpath)[1]
ax.set_title('This is a special font: {}'.format(fname), fontproperties=prop)
ax.set_xlabel('This is the default font')

print(fpath) will show you where you should put the .ttf.

You can see the output here:

Answered By: bPiMin

Leave a Reply

Your email address will not be published. Required fields are marked *