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
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 .
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.
You can set the fontsize argument, change how Matplotlib treats fonts in general, or even changing the figure size.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With