器→工具, 工具软件

Matplotlib中文乱码解决方案

钱魏Way · · 2,143 次浏览
!文章内容如有错误或排版问题,请提交反馈,非常感谢!

在使用 matplotlib 默认情况会出现乱码问题,原则上 matplotlib 是支持中文的,只是在配置信息里没有中文字体的相关信息。

Windows 下中文乱码解决方案

解决方案一:修改配置文件

matplotlib 从配置文件 matplotlibrc 中读取配置,字体相关内容也在其中。查询当前 matplotlibrc 所在目录,可以用 get_configdir() 函数:

import matplotlib

matplotlib.get_configdir()

通常存放位置:lib\site-packages\matplotlib\mpl-data\matplotlibrc

涉及到字体部分的设置内容为:

#font.family: sans-serif
#font.style: normal
#font.variant: normal
#font.weight: normal
#font.stretch: normal
## note that font.size controls default text sizes. To configure
## special text sizes tick labels, axes, labels, title, etc, see the rc
## settings for axes and ticks. Special text sizes can be defined
## relative to font.size, using the following values: xx-small, x-small,
## small, medium, large, x-large, xx-large, larger, or smaller
#font.size: 10.0
#font.serif: DejaVu Serif, Bitstream Vera Serif, Computer Modern Roman, New Century Schoolbook, Century Schoolbook L, Utopia, ITC Bookman, Bookman, Nimbus Roman No9 L, Times New Roman, Times, Palatino, Charter, serif
#font.sans-serif: DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#font.cursive: Apple Chancery, Textile, Zapf Chancery, Sand, Script MT, Felipa, cursive
#font.fantasy: Comic Sans MS, Chicago, Charcoal, Impact, Western, Humor Sans, xkcd, fantasy
#font.monospace: DejaVu Sans Mono, Bitstream Vera Sans Mono, Computer Modern Typewriter, Andale Mono, Nimbus Mono L, Courier New, Courier, Fixed, Terminal, monospace

matplotlib 默认使用的 font.family 是 sans-serif,即无衬线字体,可以看到在 font.sans-serif 中设置的全部为西文字体,这里的设置和 css 样式文件中设置差不多,只需要添加系统存在的字体名称即可(需要注意的是,matplotlib:

只支持 ttf 格式的字体),设置时需要将注释符号 # 去除。

解决方案二:重载配置文件

import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['font.serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号 '-' 显示为方块的问题, 或者转换负号为字符串

解决方案三:自定义字体

import numpy as np
import pylab as pl
import matplotlib.font_manager as fm

myfont = fm.FontProperties(fname=r'D:\Fonts\simkai.ttf') # 设置字体
t = np.arange(0.0, 2.0*np.pi, 0.01) # 自变量取值范围
s = np.sin(t) # 计算正弦函数值
z = np.cos(t) # 计算余弦函数值
pl.plot(t, s, label='正弦')
pl.plot(t, z, label='余弦')
pl.xlabel('x-变量', fontproperties=myfont, fontsize=24) # 设置标签
pl.ylabel('y-正弦余弦函数值', fontproperties=myfont, fontsize=24)
pl.title('sin-cos 函数图像', fontproperties=myfont, fontsize=32) # 图像标题
pl.legend(prop=myfont)
pl.show()

Linux 下 Matplotlib 中文乱码解决方案

关于 Matplotlib 画图出现的中文显示为方框的问题,网上的很多解决方案是针对 Windows 系统的。在 Linux 会出现问题的主要原因是 matplotlib 找不到相应的中文字体。

解决方案:

将 Windows 中的中文字体安装进 Linux

比如将 simfang.ttf、simkai.ttf 复制到 /usr/share/font 目录下即可

是否安装成功可通过以下命名查看:

jovyan@9f5db12af44c:~$ fc-list:lang=zh
/usr/share/fonts/simkai.ttf: KaiTi,楷体:style=Regular,Normal,obyčejné,Standard,Κανονικά,Normaali,Normál,Normale,Standaard,Normalny,Обычный,Normálne,Navadno,Arrunta
/usr/share/fonts/simfang.ttf: FangSong,仿宋:style=Regular,Normal,obyčejné,Standard,Κανονικά,Normaali,Normál,Normale,Standaard,Normalny,Обычный,Normálne,Navadno,Arrunta

将上述字体复制到 matplotlib 字体目录下

路径查询方法:

import matplotlib as mpl

print(mpl.matplotlib_fname())

打印的内容为:/opt/conda/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc

则字体目录为:/opt/conda/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf修改配置文件

配置文件即为刚才查询得到的 /opt/conda/lib/python3.7/site-packages/matplotlib/mpl-data/matplotlibrc

打开后去除下面三个配置项的注释,并将添加的字体英文名条件到 font.sans-serif 的最前面

font.family: sans-serif
font.sans-serif: FangSong, Kaiti, DejaVuSans, BitstreamVeraSans, ComputerModernSansSerif, LucidaGrande, Verdana, Geneva, Lucid, Arial, Helvetica, AvantGarde, sans-serif
axes.unicode_minus: True ## use unicode for the minus symbol
## rather than hyphen. See
## http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes

删除缓存

一般情况下,缓存在~/.cache/matplotlib目录下,但也有些会在~/.matplotlib目录下。直接执行如下命令即可。

rm -rf ~/.cache/matplotlib
rm -rf ~/.matplotlib

最后重新执行序即可正常显示中文了。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注