How to Change font style in matplotlib – Custom font

By default, Matplotlib visualizations might be ugly. Fortunately for you, a few lines of code can change a lot. Today, we’ll examine typeface changes and discuss why they’re typically a smart move.

After completing this tutorial, you will learn how to change the font style of matplotlib by using custom font.

In this post, we’ll look at how to use matplotlib to modify the font family used in our graph. In truth, matplotlib supports a wide range of typefaces; all required to implement them is to give the name as the value of the fontname option.

Approach:

  1. Import the necessary library.
  2. Assemble data
  3. Set a new typeface.
  4. Usually, data are plotted.
  5. Display graph

Let’s see how default stylings appear. Without information, there can be no information representation, subsequently, we should initially lay out a particular dataset.

import pandas as p
import matplotlib.pyplot as pl

df = p.DataFrame({'percentage': pd.Series([34,23,65,37,89,64], index=['A', 'B', 'C','D','E','F'])})
print(df)
fig, ax = pl.subplots(figsize=(7,4))
df.iloc[::-1].plot(kind='barh', legend = False, ax=ax)
ax.set_xlabel('Percentage',fontsize=15)
ax.set_ylabel('Type',fontsize=15)
pl.title('By Amandeep', size=20)
pl.show()

The output will be:

 perc
A 34
B 23
C 65
D 37
E 89
F 64

And the graph will look like this:

As you can see, the typefaces are aesthetically pleasing, however, I am unaware of any brands that utilize DejaVu Sans as their preferred font. Next, let’s look at how to alter it with the help of using built-in fonts.
Fonts that are already on your computer are simple to utilize with Matplotlib. The typefaces that are available may be listed using the following line of code:

import matplotlib.font_manager

matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')

It will print you a list of fonts which is present in your system.

We now have to tell Matplotlib to utilize our unique font. Consider changing the font for the labels and ticks on a bar chart.

In this case, we will use two different fonts ‘Bradley Hand ITC’ and ‘Algerian’ by adding the command font=’YOUR FONT NAME’ in our previous Python Code.

import pandas as p
import matplotlib.pyplot as pl

df = p.DataFrame({'percentage': p.Series([34,23,65,37,89,64], index=['A', 'B', 'C','D','E','F'])})
print(df)
fig, ax = pl.subplots(figsize=(7,4))
df.iloc[::-1].plot(kind='barh', legend = False, ax=ax)
ax.set_xlabel('Percentage',font='Bradley Hand ITC',fontsize=15)
ax.set_ylabel('Type',font='Bradley Hand ITC',fontsize=15)
pl.title('By Amandeep',font='Algerian', size=20)
pl.show()

The output will be:

Add a custom font in matplotlib from a font file

You can utilize a custom text style regardless of whether your working framework has it introduced.
Involving Comic Sans, for instance, we initially download our text style prior to saving it on the circle (way/to/textual style/).

The code will be:

from matplotlib import font_manager

f_dir = ['way/to/textual style/']
f_fle = font_manager.findSystemFonts(fontpaths=f_dir)

for f_fle in f_fle:
    font_manager.fontManager.addfont(f_fle)

# set font family globally
plt.rcParams['font.family'] = 'Comic Sans'

So in this way, we can change the font style in matplotlib.

I hope you like this article.

Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *