Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Load and plot a remote font with Matplotlib

2i2c
Project Jupyter

As part of my sphinx-social-previews prototype, I wanted to be able to use the Roboto Font from Google in image previews. However, Roboto is often not loaded on your local filesystem, so it took some digging to figure out how to make it possible to load via Matplotlib’s text plotting functionality.

Here’s the solution that finally worked for me, inspired from this Tweet with a similar implementation from the dmol book.

Below I’ll use the Fira Code font from Mozilla but you could do this with any open font that you have the .ttf file for.

Create a temporary folder and download the font file

I’ll show how to do this with a local folder, so it’ll re-download each time you run the code. Alternatively you could download the font locally and just register the path instead of downloading it:

First, download the .ttf of the font locally via urlretrieve. For example, the Fira Code font from Mozilla is located at this URL. To download it locally into a temporary folder using the tempfile.mkdtemp function, run this code:

Now that the file is loaded, we can link it using Matplotlib’s font_manager API. This allows you to register fonts that Matplotlib knows how to use.

Make a plot with this font

Now that we’ve registered the font, we can plot it with ax.text. To do so, use the plt.rc_context context manager to temporarily update our default font:

And that’s it!