首先运行以下命令来查看matplotlib所在位置:
echo -e "import matplotlib\nprint(matplotlib.matplotlib_fname())" | python3比如 /usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc,将simhei.ttf拷贝到字体目录./matplotlib/mpl-data/fonts/ttf
查询得到缓存目录,然后清除这个目录
echo -e "import matplotlib\nprint(matplotlib.get_cachedir())" | python3
rm -rf ~/.matplotlib这样处理后,代码中不再需要指定字体
font.family : sans-serif
font.sans-serif : SimHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
axes.unicode_minus : False这个更灵活不需要修改配置文件
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
运行如下代码验证
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
#如果修改了配置文件,下面两行就不必要了
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
if __name__ == '__main__':
plt.plot([-1,0,1,2,3])
plt.title("天王盖地虎")
plt.show()- https://www.jianshu.com/p/15b5189f85a3
- https://www.jianshu.com/p/d1eeaa58ff4e
- https://www.zhihu.com/question/25404709
- ttc字体文件也是可以使用的
ttc字体文件也是可以使用的,但需要修改matplotlib/font_manager.py文件。在函数get_fontext_synonyms中添加'ttc'这一选项。
def get_fontext_synonyms(fontext):
"""
Return a list of file extensions extensions that are synonyms for
the given file extension *fileext*.
"""
return {'ttf': ('ttf', 'otf', 'ttc'),
'otf': ('ttf', 'otf'),
'afm': ('afm',)}[fontext]具体可以参考Matplotlib在Mac上的中文支持問題。