dindom
dindom

Reputation: 691

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

Upvotes: 32

Views: 25158

Answers (3)

gitnoob
gitnoob

Reputation: 460

2023 Update

I came across this issue recently and found this the most simple way to deal with it. It does not fiddle with sys paths.

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()

Note that this requires matplotlib>=3.2. For older versions, the addfont method doesn't exist and the above will fail with AttributeError: 'FontManager' object has no attribute 'addfont'

Upvotes: 35

SCKU
SCKU

Reputation: 833

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'

Upvotes: 8

Geotob
Geotob

Reputation: 2945

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.

Upvotes: 35

Related Questions