Matplotlib visualizations can be an eyesore by default. Lucikly for you, a lot can be tweaked with a couple of lines of code. Today we’ll take a look at changing fonts and explain why it is generally a good idea.
The article is structured as follows:
Custom fonts – Why?
Why not? The default ones won’t get you far. If your company has a distinct branding, why not use it whenever possible?
Let’s take a look at how default stylings look like. There’s no data visualization without data, so let’s declare a simple dataset first. It contains dummy quarterly sales for an imaginary company:
Here’s how the dataset looks like:
Let’s visualize this data with both line and scatter plots. We’ll keep most of the default stylings and just remove the top and right spines:
Here’s the visualization:
As you can see, the fonts look decent, but I don’t know a single brand that uses DejaVu Sans as their font of choice. Let’s see how to change it next.
Using built-in fonts
Matplotlib makes it easy to use fonts installed on your machine. You can use the following code snippet to list the first ten available fonts:
Here are the results:
Remove the `[:10]` if you want the entire list. You can specify the value for the `font` parameter to use a font of interest in either title or the axis labels.
The following code snippet shows you how to use Courier New font in the title:
Here’s how the visualization looks like:
But did you know there’s no need to install the font before using it? All you need is a TTF file. Let’s explore how that works next.
Using custom fonts from a TTF file
To follow along, please download the Merriweather font from here (or any other). Unzip the file and copy the path to the folder.
From here, we can use the `font_manager` from Matplotlib to add fonts from a file. You’ll want to add the fonts one by one inside the loop.
Once added, we’ll set the entire Matplotlib font family to Merriweather, so we don’t have to specify the font everywhere manually.
Once that is done, you can make the visualization as you usually would:
The results are shown in the following figure:
And that’s how easy it is to add custom fonts to Matplotlib! Let’s wrap things up next.
Today’s article was short but to the point. You’ve learned how to incorporate your branding into data visualizations, an essential skill if you want to send a consistent message across all mediums.
Stay tuned to the blog if you’ve liked this piece – a bunch more similar articles are coming soon.
- Top 5 Books to Learn Data Science in 2021
- Ridgeline Plots: The Perfect Way to Visualize Data Distributions with Python
- Python Dictionaries: Everything You Need to Know
- How to Send Beautiful Emails with Python – The Essential Guide
- Are the New M1 Macbooks Any Good for Data Science? Let’s Find Out