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:
- Download fonts from the sources listed above.
- Install fonts on your system. Usually, double-click on the
.ttffile 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
- Clear matplotlib cache by running the following command on your terminal
rm -fr ~/.cache/matplotlib
- If you're using a Jupyter notebook, this is a good time to restart it.
- 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")
- 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
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
- On Linux
and also try with
Then, just repeat steps 2 to 6.
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");