问题描述:
代码使用 jupyter 运行
在一些用于解决matplotlib绘图,汉字乱码问题的博客中,
有可能会让读者在安装 matplotlib 后添加新字体,接着需要删除字体缓存,然后再重新加载字体库,这时候可能会用到:
import matplotlib.font_manager as font_manager
font_manager._rebuild()
然后就报错了
原因分析:
至少在 matplotlib 3.4.2 中,字体管理器没有属性_rebuild,后续版本就更不好说了。
解决方案:
反正font_manager._rebuild()
的目的是清除 matplotlib 字体缓存,那么就有替代方案了。
先键入如下代码:
import shutil
import matplotlib
shutil.rmtree(matplotlib.get_cachedir())
然后重新启动jupyter内核。
使用如下代码检查新添加字体是否存在
for font in font_manager.fontManager.ttflist:
print(font)
使用如下代码将显示 matplotlib 中所有可用的字体
import matplotlib.font_manager
from IPython.core.display import HTML
def make_html(fontname):
return "<p>{font}: <span style='font-family:{font}; font-size: 24px;'>{font}</p>".format(font=fontname)
code = "\n".join([make_html(font) for font in sorted(set([f.name for f in matplotlib.font_manager.fontManager.ttflist]))])
HTML("<div style='column-count: 2;'>{}</div>".format(code))