Introduction

Fonts are one of the most important aspects of a good visualization. Choosing the right font can make a huge difference in the readability and overall quality of a chart. The goal of this post is to show how to import and use custom fonts in Matplotlib. For this purpose, two different fonts from two different sources are going to be used in today's post:

  • Hydrophilia Iced from Floodfonts. Here you can download a zipped folder that contains the font as both .otf and .ttf types. Make sure you install the .ttf version for Matplotlib.
  • Special Elite. Available from Google Fonts here.

Steps

  1. Download fonts from the sources listed above.
  2. Install fonts on your system. Usually, double-click on the .ttf file and then click on the Install button in the window that pops up. Note that Matplotlib handles fonts in True Type Format (.ttf), so make sure you install fonts ending in .ttf.
  3. Clear matplotlib cache by running the following command on your terminal
rm -fr ~/.cache/matplotlib
  1. If you're using a Jupyter notebook, this is a good time to restart it.
  2. Run the following code to tell Matplotlib to look for fonts in your system (it will return a list with font paths)
from matplotlib import font_manager
font_manager.findSystemFonts(fontpaths=None, fontext="ttf")
  1. Check the fonts are accesible by Matplotlib with
font_manager.findfont("Hydrophilia Iced") # Test with "Special Elite" too

The result should be a path to the font like the following

'/home/tomas/.local/share/fonts/HydrophiliaIced-Regular.ttf'

What to do if it fails

If the font is unreachable by Matplotlib you will have a message like

findfont: Font family ['Hydrophilia Iced'] not found. Falling back to DejaVu Sans.

Try with adding your font into the system library.

  • On OS X
~/Library/Fonts/
  • On Linux
/usr/share/fonts/truetype

and also try with

/usr/share/fonts

Then, just repeat steps 2 to 6.

Plot

Now that we've covered how to make fonts accesible by Matplotlib, it's a good time to plot something and see how these two new fonts look like!

import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.scatter([1, 2, 3, 4], [1, 2, 3, 4], s=500, color="darkcyan")
plt.text(2.5, 2, "Isn't it fantastic?!", fontname="Special Elite", fontsize=24)
plt.xlabel("Horizontal Label", fontname="Hydrophilia Iced", fontsize=20)
plt.ylabel("Vertical label too!", fontname="Hydrophilia Iced", fontsize=20)
plt.title("We can write better looking titles!", fontsize=28,fontname="Special Elite");
Animation with python

Animation

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!