how to set up a custom font with custom path to matplotlib global font?

There is a custom font in my app

app_path='/home/user1/myapp'
fname='/home/user1/myapp/font/myfont.ttf'

To setup globlal font to matplotlib,the docs said like this:

plt.rcParams['font.sans-serif']=['xxx font']

But it only works when the font already in system font path,and I have to use my custom font in my app path '/home/user1/myapp/font/myfont.ttf'

I know there is a way like this:

fname='/home/user1/myapp/font/myfont.ttf'
myfont=fm.FontProperties(fname=fname)
ax1.set_title('title test',fontproperties=myfont)

But that is not what I want,I don't want to set 'fontproperties' all the time,because there are some much code to change


Solved the problem like this:

import matplotlib.font_manager as font_manager

font_dirs = ['/my/custom/font/dir', ]
font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
font_list = font_manager.createFontList(font_files)
font_manager.fontManager.ttflist.extend(font_list)

mpl.rcParams['font.family'] = 'My Custom Font'

The fontpaths kwarg can also be a string in case you only have a single directory to import from.


2021 Update

I came across this issue recently and found this the most simple way to deal with it.

Adding the font is the important part, otherwise, the font will not be detected:

import matplotlib.pyplot as plt
from matplotlib import font_manager

font_path = 'Inter-Regular.otf'  # Your font path goes here
font_manager.fontManager.addfont(font_path)
prop = font_manager.FontProperties(fname=font_path)

plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = prop.get_name()

For newer matplotlib module (e.g. version >=3.2)
createFontList is deprecated.

Hoever, you can make a font entry with ttf file path and custom name,
then add it to fontManager.ttflist, and assign matplotlib.rcParams['font.familt'] to that name.
Now you can start to make a plot without 'fontproperties' etc.

import matplotlib as mpl
import matplotlib.font_manager as fm

fe = fm.FontEntry(
    fname='your custom ttf file path',
    name='your custom ttf font name')
fm.fontManager.ttflist.insert(0, fe) # or append is fine
mpl.rcParams['font.family'] = fe.name # = 'your custom ttf font name'