200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > Python用matplotlib画图是中文无法显示问题及Font family [‘SimSun‘] not found

Python用matplotlib画图是中文无法显示问题及Font family [‘SimSun‘] not found

时间:2021-03-07 21:24:22

相关推荐

Python用matplotlib画图是中文无法显示问题及Font family [‘SimSun‘] not found

1、matplotlib画图,添加中文图例和坐标标签,报错

# -*- coding: utf-8 -*-import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y = [2.3, 3.4, 1.2, 6.6, 7.0]# 绘制散点图plt.scatter(x, y, color='r' )# 添加图例plt.legend(["ICDAR"],loc='upper left')plt.xlabel('年份')plt.ylabel('人口')plt.title('人口增长')plt.savefig('scatter.png')

结果中文无法显示

按照网上的方法加入下面代码

import matplotlib.pyplot as pltplt.rcParams["font.sans-serif"]=["SimHei"]plt.rcParams["axes.unicode_minus"]=False# 或者使用下面宋体import matplotlib.pyplot as pltplt.rcParams['font.family'] = 'SimSun'

结果报错,字体不存在

findfont: Font family ['sans-serif'] not found. Falling back to DejaVu Sans

findfont: Font family ['SimSun'] not found. Falling back to DejaVu Sans.

2、在终端python 的环境下,查看字体路径

import matplotlib print(matplotlib.matplotlib_fname())

进入路径,查看结构
进入fonts,此路径存放字体

3、下载字体

Stylify-Me/.fonts/SimSun.ttf at master · SparksFly8/Stylify-Me · GitHub

文件 SimSun.ttf复制到 /opt/conda/lib/python3.8/site-packages/matplotlib/mpl-data/fonts/ttf 路径下。

4、修改matplotlibrc文件

修改/opt/conda/lib/python3.8/site-packages/matplotlib/mpl-data/mpl-data/matplotlibrc,修改内容如下:找到font.sans-serif,添加SimSun。。看别人说要去掉前面的#,但我觉得原来这样别的字体能用,这样应该也能用,好像## (两个##加空格)才是注释!

#font.serif: DejaVu Serif, .....

#font.sans-serif: SimSun, DejaVu Sans, Bitstream Vera Sans, ....

5、修改matplotlib的缓冲配置内容

在终端python 的环境下,输入如下指令,查看matplotlib的字体缓存路径

import matplotlibmatplotlib.get_cachedir()

看别人说使用rm -rf +路径 删除缓存,然后重启,由于我用服务器,重启要找管理员。

于是打开缓存'/root/.cache/matplotlib',查看内容如下,原来字体是在这里配置的,

ttflist中添加自己的模块,路径"fname": "fonts/ttf/SimSun.ttf", ''name'': ''SimSun'',其它内容和别的模块一致就行,保存文件,即可成功

{

"_version": 330,

"_FontManager__default_weight": "normal",

"default_size": null,

"defaultFamily": {

"ttf": "DejaVu Sans",

"afm": "Helvetica"

},

"afmlist": [

.....

],

"ttflist": [

{

"fname": "fonts/ttf/SimSun.ttf",

"name": "SimSun",

"style": "normal",

"variant": "normal",

"weight": 400,

"stretch": "normal",

"size": "scalable",

"__class__": "FontEntry"

},

{

"fname": "fonts/ttf/DejaVuSerif.ttf",

"name": "DejaVu Serif",

"style": "normal",

"variant": "normal",

"weight": 400,

"stretch": "normal",

"size": "scalable",

"__class__": "FontEntry"

},

6、中文显示成功

Python用matplotlib画图是中文无法显示问题及Font family [‘SimSun‘] not found 不用清空缓存 重启服务器

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。