logo头像
Snippet 博客主题

matplotlib不支持中文和符号的解决办法

现象

中文乱码 和 - 负号显示为方块

报错类型

1
Mac UserWarning: findfont: Font family ['SimHei'] not found

产生原因:matplotlib: plotting with Python 默认不支持中文字符和符号,缺少 SimHei 字体.

解决方法

1、下载 SimHei 字体

1
地址:https://www.fontpalace.com/font-download/SimHei/

2、查找字体存在的目录

2.1 进入Python3环境

1
~: python3

2.2 import matplotlib库并打印路径

1
2
3
4
5
6
7
Python 3.7.3 (default, Nov 15 2019, 04:04:52)
[Clang 11.0.0 (clang-1100.0.33.16)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
'/Users/mk/Library/Python/3.7/lib/python/site-packages/matplotlib/mpl-data/matplotlibrc'
>>>

复制路径 /Users/mk/Library/Python/3.7/lib/python/site-packages/matplotlib/mpl-data/matplotlibrc 到剪切板

2.3 获取字体存放路径

一般路径是:/Users/mk/Library/Python/3.7/lib/python/site-packages/matplotlib/mpl-data/fonts/ttf/

将下载好的字体 SimHei 复制到上面的路径

3、修改 matplotlibrc 配置文件

matplotlibrc 的路径就是2.2种获取的路径

3.1 打开 font.family

1
2
3
4
5
6
7
8
## The font.size property is the default font size for text, given in pts.
## 10 pt is the standard value.

font.family : sans-serif
#font.style : normal
#font.variant : normal
#font.weight : normal
#font.stretch : normal

3.2 打开 font.serif 和 font.sans-serif 并添加 SimHei

1
2
3
4
5
6
## small, medium, large, x-large, xx-large, larger, or smaller
#font.size : 10.0
font.serif : SimHei, 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 : SimHei, 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, ImpactWestern, Humor Sans, xkcd, fantasy

3.3 将 axes.unicode_minus 的值 True改成False

1
2
3
4
5
6
7
8
9
10
11
12
#axes.spines.bottom : True
#axes.spines.top : True
#axes.spines.right : True
axes.unicode_minus : False ## use unicode for the minus symbol
## rather than hyphen. See
## http://en.wikipedia.org/wiki/Plus_and_minus_signs#Character_codes
#axes.prop_cycle : cycler('color', ['1f77b4', 'ff7f0e', '2ca02c', 'd62728', '9467bd', '8c564b', 'e377c2', '7f7f7f', 'bcbd22', '17becf'])
## color cycle for plot lines as list of string
## colorspecs: single letter, long name, or web-style hex
## Note the use of string escapes here ('1f77b4', instead of 1f77b4)
## as opposed to the rest of this file.
#axes.autolimit_mode : data ## How to scale axes limits to the data.

4、删除缓存文件

删除 /Users/mk/.matplotlib 文件夹下的 fontlist-v310.jsontex.cache

5、重新运行python

备注:文中路径中 /mk/ 为笔者电脑用户名,请根据实际情况修改。