首页 > 分享 > matplotlib字体查找机制探索

matplotlib字体查找机制探索

问题来源

matplotlib文本字体设置的成败关键在于是否能够准确找到我们配置的字体并应用,matplotlib是怎么样查找字体的呢?

matplotlib字体查找机制

根据后台绘制模块backend_agg.py源码可知,与绘制文本选择字体相关的源码有:

def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): # docstring inherited if ismath: return self.draw_mathtext(gc, x, y, s, prop, angle) flags = get_hinting_flag() font = self._get_agg_font(prop) if font is None: return None # We pass '0' for angle here, since it will be rotated (in raster # space) in the following call to draw_text_image). font.set_text(s, 0, flags=flags) 1234567891011121314'

def _get_agg_font(self, prop): """ Get the font for text instance t, caching for efficiency """ fname = findfont(prop) font = get_font(fname) font.clear() size = prop.get_size_in_points() font.set_size(size, self.dpi) return font 123456789101112'

由此可知,选择字体的关键在findfont和get_font这两个函数上。

由from matplotlib.font_manager import findfont, get_font可知,这两个函数属于font_manager模块。

The findfontfunction returns the best TrueType (TTF) font file in
the local or system font path that matches the specified
FontPropertiesinstance.
The FontManager.findfont method does a
nearest neighbor search to find the font that most closely matches
the specification. If no good enough match is found, the default
font is returned.

def findfont(self, prop, fontext='ttf', directory=None, fallback_to_default=True, rebuild_if_missing=True): """ Find a font that most closely matches the given font properties. Parameters ---------- prop : str or `~matplotlib.font_manager.FontProperties` The font properties to search for. This can be either a `.FontProperties` object or a string defining a `fontconfig patterns`_. fontext : {'ttf', 'afm'}, default: 'ttf' The extension of the font file: - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf) - 'afm': Adobe Font Metrics (.afm) directory : str, optional If given, only search this directory and its subdirectories. fallback_to_default : bool If True, will fallback to the default font family (usually "DejaVu Sans" or "Helvetica") if the first lookup hard-fails. rebuild_if_missing : bool Whether to rebuild the font cache and search again if the first match appears to point to a nonexisting font (i.e., the font cache contains outdated entries). Returns ------- str The filename of the best matching font. Notes ----- This performs a nearest neighbor search. Each font is given a similarity score to the target font properties. The first font with the highest score is returned. If no matches below a certain threshold are found, the default font (usually DejaVu Sans) is returned. The result is cached, so subsequent lookups don't have to perform the O(n) nearest neighbor search. See the `W3C Cascading Style Sheet, Level 1 <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation for a description of the font finding algorithm. .. _fontconfig patterns: https://www.freedesktop.org/software/fontconfig/fontconfig-user.html """ # Pass the relevant rcParams (and the font manager, as `self`) to # _findfont_cached so to prevent using a stale cache entry after an # rcParam was changed. rc_params = tuple(tuple(rcParams[key]) for key in [ "font.serif", "font.sans-serif", "font.cursive", "font.fantasy", "font.monospace"]) filename = self._findfont_cached( prop, fontext, directory, fallback_to_default, rebuild_if_missing, rc_params) return os.path.realpath(filename)

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263'

if not os.path.isfile(result): if rebuild_if_missing: _log.info( 'findfont: Found a missing font file. Rebuilding cache.') _rebuild() return fontManager.findfont( prop, fontext, directory, rebuild_if_missing=False) else: raise ValueError("No valid font could be found") 123456789 结论

根据文档描述:

findfont会根据字体设置的一系列属性(字体家族、大小等)进行评分来查找最合适的字体,如果找不到合适字体就会使用默认字体(DejaVu Sans),而不是简单的直接应用字体设置。findfont是通过_findfont_cached查找字体,也就是直接去字体缓存查找!所以有时候新安装字体没有加入matplotlib的字体缓存时是无法查找到的。如果字体缓存丢失,可以使用_rebuild()重建。

相关知识

python 画心形线 matplotlib
Python的可视化包 – Matplotlib
如何在matplotlib中添加笔画符号D?
鸢尾花数据可视化——基于matplotlib
Python中的数据可视化:Matplotlib基础与高级技巧
探索字体设计的奥秘:常用字体设计软件大揭秘
查找: 关键字=中药产业
查找: 关键字=农业土壤
查找: 关键字=季节调整
查找: 关键字=绿色建筑

网址: matplotlib字体查找机制探索 https://m.huajiangbk.com/newsview702255.html

所属分类:花卉
上一篇: 细花中文字体下载免费下载和在线预
下一篇: angular