150

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).

2
  • Glad it helped :) Can you post the code that causes this error? I haven't seen this error myself but here's some links that may help you. matplotlib.1069221.n5.nabble.com/… matplotlib.1069221.n5.nabble.com/Fonts-not-found-td12936.html Commented Jan 24, 2014 at 23:33
  • The code which generates the problem is: hfont = {'fontname':'Helvetica'} plt.annotate('Country ', (0.17,0.95), xytext=None, xycoords='figure fraction',size=28, color='red', horizontalalignment = 'left', **hfont) and the error is /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/m‌​atplotlib/font_manager.py:1236: UserWarning: findfont: Font family ['Helvetica'] not found. Falling back to Bitstream Vera Sans (prop.get_family(), self.defaultFamily[fontext])) instead if I use as fontname Comic Sans MS as in your example, the code works. Commented Jan 26, 2014 at 17:54

8 Answers 8

166

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

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

plt.title('title',**csfont)
plt.xlabel('xlabel', **hfont)
plt.show()
Sign up to request clarification or add additional context in comments.

4 Comments

I tried and it works! It is exactly what I was looking for. However, for some fonts I have the following error message (not for all): /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/font_manager.py:1236: UserWarning: findfont: Font family ['Helvetica'] not found. Falling back to Bitstream Vera Sans (prop.get_family(), self.defaultFamily[fontext])). How can I install Helvetica in the set of fonts known by matplotlib?
find the fontList.cache file, you can use only those listed there. Alternatively take a look here stackoverflow.com/questions/20206906/…
following up on the above comment. To find your fontList.cache file, use matplotlib.get_cachedir()
Thanks! Since this is just unpacking a dictionary with the ** syntax, I tried simply doing plt.title('title', fontname = 'monospace') and it works as well!
103

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

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

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

Comments

45

I prefer to employ:

from matplotlib import rc
#rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('font',**{'family':'serif','serif':['Times']})
rc('text', usetex=True)

The last line ensures that tick labels are also in the correct font.

2 Comments

Great way to change the font globally, I was looking for this. The last line is not necessary, not sure what Tex has to do with this. If you get an error because the font you want is not found by Matplotlib, check out this link: scentellegher.github.io/visualization/2018/05/02/…
usetex=False works just as well. True gives runtime errors because it's looking for the latex package.
13
import pylab as plb
plb.rcParams['font.size'] = 12

or

import matplotlib.pyplot as mpl
mpl.rcParams['font.size'] = 12

2 Comments

incredibly enough this is exactly the command I was looking for. definitely not what OP was asking though
The asker clearly said in the question that he is not looking to change the font size.
11

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')

plt.show()

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

You can see the output here: https://matplotlib.org/gallery/api/font_file.html

2 Comments

Is there any way to set fontproperties globally so you don't have to specify it with every call to e.g. set_title(), set_xlabel(), etc.?
^ To answer my own question: stackoverflow.com/questions/35668219
6

I use

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Arial"

to set the font of the entire plot.
If you want to use a different font e.g. for the title, you can use aidnani8's solution on top of that. Setting first the default font for the figure with the line above can come handy if you want to use the same font for several items though.

1 Comment

WARNING:matplotlib.font_manager:findfont: Font family 'Arial' not found.
3

Just a reminder to those using LaTeX in their plots. LaTeX rendering should be enabled manually by:

plt.rcParams.update({
    "text.usetex": True,
    "font.family": 'Times New Roman'
})

Comments

0
  • Access the full list of available fonts [assuming you have installed matplotlib]:
import matplotlib # matplotlib.__version__ # '3.9.4'
import matplotlib.pyplot as plt
from natsort import natsorted # pip install natsort
print(natsorted(matplotlib.font_manager.get_font_names()))

['Abyssinica SIL', 'Ani', 'AnjaliOldLipi', 'C059', 'Chandas', 'Chilanka', 'D050000L', 'DejaVu Math TeX Gyre', 'DejaVu Sans', 'DejaVu Sans Display', 'DejaVu Sans Mono', 'DejaVu Serif', 'DejaVu Serif Display', 'Dhurjati', 'Droid Sans Fallback', 'Dyuthi', 'FreeMono', 'FreeSans', 'FreeSerif', 'Gargi', 'Garuda', 'Gayathri', 'Gidugu', 'Gubbi', 'Gurajada', 'Jamrul', 'KacstArt', 'KacstBook', 'KacstDecorative', 'KacstDigital', 'KacstFarsi', 'KacstLetter', 'KacstNaskh', 'KacstOffice', 'KacstOne', 'KacstPen', 'KacstPoster', 'KacstQurn', 'KacstScreen', 'KacstTitle', 'KacstTitleL', 'Kalapi', 'Kalimati', 'Karumbi', 'Keraleeyam', 'Khmer OS', 'Khmer OS System', 'Kinnari', 'LKLUG', 'LakkiReddy', 'Laksaman', 'League Spartan', 'Liberation Mono', 'Liberation Sans', 'Liberation Sans Narrow', 'Liberation Serif', 'Likhan', 'Lohit Assamese', 'Lohit Bengali', 'Lohit Devanagari', 'Lohit Gujarati', 'Lohit Gurmukhi', 'Lohit Kannada', 'Lohit Malayalam', 'Lohit Odia', 'Lohit Tamil', 'Lohit Tamil Classical', 'Lohit Telugu', 'Loma', 'Mallanna', 'Mandali', 'Manjari', 'Meera', 'Mitra ', 'Mukti', 'NATS', 'NTR', 'Nakula', 'Navilu', 'Nimbus Mono PS', 'Nimbus Roman', 'Nimbus Sans', 'Nimbus Sans Narrow', 'Norasi', 'Noto Mono', 'Noto Sans CJK JP', 'Noto Sans Mono', 'Noto Serif CJK JP', 'OpenSymbol', 'P052', 'Padauk', 'Padauk Book', 'Pagul', 'Peddana', 'Phetsarath OT', 'Ponnala', 'Pothana2000', 'Potti Sreeramulu', 'Purisa', 'Rachana', 'RaghuMalayalamSans', 'Ramabhadra', 'Ramaraja', 'Rasa', 'RaviPrakash', 'Rekha', 'STIXGeneral', 'STIXNonUnicode', 'STIXSizeFiveSym', 'STIXSizeFourSym', 'STIXSizeOneSym', 'STIXSizeThreeSym', 'STIXSizeTwoSym', 'Saab', 'Sahadeva', 'Samanata', 'Samyak Devanagari', 'Samyak Gujarati', 'Samyak Malayalam', 'Samyak Tamil', 'Sarai', 'Sawasdee', 'Sree Krushnadevaraya', 'Standard Symbols PS', 'Suranna', 'Suravaram', 'Suruma', 'Syamala Ramana', 'TenaliRamakrishna', 'Tibetan Machine Uni', 'Timmana', 'Tlwg Mono', 'Tlwg Typewriter', 'Tlwg Typist', 'Tlwg Typo', 'URW Bookman', 'URW Gothic', 'Ubuntu', 'Ubuntu Condensed', 'Ubuntu Mono', 'Umpush', 'Uroob', 'Vemana2000', 'Waree', 'Yrsa', 'Z003', 'aakar', 'cmb10', 'cmex10', 'cmmi10', 'cmr10', 'cmss10', 'cmsy10', 'cmtt10', 'mry_KacstQurn', 'ori1Uni', 'padmaa', 'padmaa-Bold.1.1']
  • Change the font using:
# (Example) Maths fonts to match TeX Gyre Dejavu:
plt.rcParams["font.family"] = "DejaVu Math TeX Gyre"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.