Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 310
dindom Avatar asked Feb 27 '16 09:02

dindom


People also ask

How do I add fonts to Matplotlib?

Usually, double-click on the . ttf file and then click on the Install button in the window that pops up. Note that Matplotlib handles fonts in True Type Format (. ttf) , so make sure you install fonts ending in .

How do I add custom fonts to Python?

Open Fonts by clicking the Start button Picture of the Start button, clicking Control Panel, clicking Appearance and Personalization, and then clicking Fonts. Then drag your font to there. That's all. You should see this screen, drag your font here.

Can you change the font in Matplotlib?

You can set the fontsize argument, change how Matplotlib treats fonts in general, or even changing the figure size.

Where are Matplotlib fonts stored?

To map font names to font files, matplotlib has a dictionary (or json file) located in its cache directory. Note, this file is not always in the same place, but usually sits at the home directory. If you are on mac (windows), it usually sits at whereever your HOME (%HOME%) environmental variable is set to.


2 Answers

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.

like image 156
Geotob Avatar answered Sep 29 '22 16:09

Geotob


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()
like image 31
gitnoob Avatar answered Sep 29 '22 14:09

gitnoob