如何设置自定义字体与matplotlib全球字体的自定义路径? [英] how to set up a custom font with custom path to matplotlib global font?

查看:1118
本文介绍了如何设置自定义字体与matplotlib全球字体的自定义路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中有一个自定义字体

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

要将 globlal 字体设置为matplotlib,文档将如下所示:

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

已经在系统字体路径中,我必须在我的应用路径中使用我的自定义字体'/home/user1/myapp/font/myfont.ttf'



我知道有这样一个方法:

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

但是这并不是我想要的,我不想一直设置' fontproperties ',因为有很多代码需要更改

解决方

  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'] ='我的自定义字体'

fontpaths kwarg也可以是一个字符串,以防您只有一个目录从中导入。



希望这可以帮助那些未来绊倒人的人=)

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

解决方案

Just had exactly the same problem and managed to solve it 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.

Hope it helps people who stumble across this in the future =)

这篇关于如何设置自定义字体与matplotlib全球字体的自定义路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆