matplotlib在哪里找到字体以及如何添加一个新的?



首先我把我的自定义字体STKAITI.TTF/usr/local/share/fonts,然后重建字体缓存的fc-cache -fv

但是我仍然不能在matplotlib中使用它。

In [13]: matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext='ttf')
Out[13]:
['/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf',
'/usr/local/share/fonts/STKAITI.TTF', # font is here
'/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf',
'/usr/local/share/fonts/NotoSansSC-Regular.otf',
'/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf']

:

import matplotlib.pyplot as plt
In [6]: plt.rcParams["font.sans-serif"] ## this is definded in my '~/.config/matplotlib/matplotlibrc'
Out[6]:
['STKaiti', # is here
'DejaVu Sans',
'Bitstream Vera Sans',
'Computer Modern Sans Serif',
'Lucida Grande',
'Verdana',
'Geneva',
'Lucid',
'Arial',
'Helvetica',
'Avant Garde',
'sans-serif']

好吧…测试

In [7]: matplotlib.font_manager.get_fontconfig_fonts()
<ipython-input-7-b1c4039c0e25>:1: MatplotlibDeprecationWarning:
The get_fontconfig_fonts function was deprecated in Matplotlib 3.5 and will be removed two minor releases later.
matplotlib.font_manager.get_fontconfig_fonts()
Out[7]:
['/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf',
'/usr/local/share/fonts/NotoSansSC-Regular.otf',
'/usr/local/share/fonts/STKAITI.TTF', # here
'/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSansMono-Bold.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf',
'/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf']

但是!下面的方法找不到它!

In [8]: [f.name for f in matplotlib.font_manager.fontManager.ttflist]
Out[8]:
['cmb10',
'cmr10',
'STIXGeneral',
'STIXSizeOneSym',
'DejaVu Sans Mono',
'STIXSizeTwoSym',
'cmex10',
'DejaVu Serif',
'DejaVu Sans',
'cmss10',
'STIXGeneral',
'cmtt10',
'DejaVu Sans',
'cmmi10',
'STIXSizeThreeSym',
'STIXSizeTwoSym',
'STIXSizeFourSym',
'DejaVu Serif',
'STIXSizeFiveSym',
'DejaVu Sans Mono',
'DejaVu Sans Mono',
'STIXNonUnicode',
'STIXGeneral',
'cmsy10',
'DejaVu Sans',
'STIXSizeOneSym',
'STIXNonUnicode',
'STIXSizeFourSym',
'DejaVu Serif Display',
'STIXSizeThreeSym',
'DejaVu Sans Mono',
'STIXNonUnicode',
'STIXNonUnicode',
'STIXGeneral',
'DejaVu Sans',
'DejaVu Sans Display',
'DejaVu Serif',
'DejaVu Serif',
'DejaVu Sans Mono',
'DejaVu Sans',
'DejaVu Serif',
'DejaVu Serif',
'DejaVu Sans',
'DejaVu Sans Mono']

甚至:

In [10]: matplotlib.font_manager.findfont("STKaiti", rebuild_if_missing=True)
findfont: Font family ['STKaiti'] not found. Falling back to DejaVu Sans.
Out[10]: '/usr/local/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/DejaVuSans.ttf'
In [14]: matplotlib.font_manager.findfont("STIXSizeTwoSym", rebuild_if_missing=True)
Out[14]: '/usr/local/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf'
In [19]: matplotlib.font_manager.findfont("STKaiti", directory="/usr/local/share/fonts/",rebuild_if_missing=True)
findfont: Font family ['STKaiti'] not found. Falling back to DejaVu Sans.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Input In [19], in <cell line: 1>()
----> 1 matplotlib.font_manager.findfont("STKaiti", directory="/usr/local/share/fonts/",rebuild_if_missing=True)
File /usr/local/lib/python3.8/site-packages/matplotlib/font_manager.py:1307, in FontManager.findfont(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing)
1301 # Pass the relevant rcParams (and the font manager, as `self`) to
1302 # _findfont_cached so to prevent using a stale cache entry after an
1303 # rcParam was changed.
1304 rc_params = tuple(tuple(rcParams[key]) for key in [
1305     "font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
1306     "font.monospace"])
-> 1307 return self._findfont_cached(
1308     prop, fontext, directory, fallback_to_default, rebuild_if_missing,
1309     rc_params)
File /usr/local/lib/python3.8/site-packages/matplotlib/font_manager.py:1361, in FontManager._findfont_cached(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params)
1359     default_prop = prop.copy()
1360     default_prop.set_family(self.defaultFamily[fontext])
-> 1361     return self.findfont(default_prop, fontext, directory,
1362                          fallback_to_default=False)
1363 else:
1364     raise ValueError(f"Failed to find font {prop}, and fallback "
1365                      f"to the default font was disabled")
File /usr/local/lib/python3.8/site-packages/matplotlib/font_manager.py:1307, in FontManager.findfont(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing)
1301 # Pass the relevant rcParams (and the font manager, as `self`) to
1302 # _findfont_cached so to prevent using a stale cache entry after an
1303 # rcParam was changed.
1304 rc_params = tuple(tuple(rcParams[key]) for key in [
1305     "font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
1306     "font.monospace"])
-> 1307 return self._findfont_cached(
1308     prop, fontext, directory, fallback_to_default, rebuild_if_missing,
1309     rc_params)
File /usr/local/lib/python3.8/site-packages/matplotlib/font_manager.py:1364, in FontManager._findfont_cached(self, prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params)
1361         return self.findfont(default_prop, fontext, directory,
1362                              fallback_to_default=False)
1363     else:
-> 1364         raise ValueError(f"Failed to find font {prop}, and fallback "
1365                          f"to the default font was disabled")
1366 else:
1367     _log.debug('findfont: Matching %s to %s (%r) with score of %f.',
1368                prop, best_font.name, best_font.fname, best_score)
ValueError: Failed to find font DejaVu Sans:style=normal:variant=normal:weight=normal:stretch=normal:size=16.0, and fallback to the default font was disabled

那么哪个方法真正定义了matplotlib可以使用的字体,我如何将我的字体添加到它?

所以我有一点麻烦,直到我弄清楚这个问题是特别给我。我使用wget下载的。ttf字体文件基本上是空shell。

对我来说有效的是下载一个zip文件并检查文件是否已经下载,然后我将文件直接复制到我从

得到的第一个目录中
from matplotlib import font_manager
font_manager.findSystemFonts(fontpaths=None, fontext="ttf")
print(font_manager.fontManager.ttflist)
我还删除了字体缓存:
rm ~/.cache/matplotlib -rf

我重新运行脚本,列表大小增加,我能够使用matplotlib中的字体。我认为这对我有帮助的原因是因为它让我看到了matplotlib从3个不同的位置提取字体的所有位置。

相关内容