matplotlib解决不显示中文问题

下载微软雅黑字体

找到字体文件夹

import matplotlib
print(matplotlib.matplotlib_fname())

以我的为例子,输出为

C:\Users\adobe\app\anaconda3\lib\site-packages\matplotlib\mpl-data\matplotlibrc

所以说,以我使用的anaconda为例子,它在lib\site-packages\matplotlib\mpl-data\matplotlibrc文件夹下面.
进入fonts\ttf目录,把第一步下载的msyh.ttf放到该目录下面

 

 

修改matplotlibrc文件

使用任何一个文件编辑器(推荐vscode),修改该文件,通过ctrl+f搜索找到

#axes.unicode_minus  : True    ## use unicode for the minus symbol
#font.family         : sans-serif
#font.sans-serif     : DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

分别修改为以下三行

axes.unicode_minus  : False    ## use unicode for the minus symbol
font.family         : Microsoft YaHei
font.sans-serif     : Microsoft YaHei, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

解释:

  1. 首先三行都需要删除第一个#,取消注释
  2. 第一行,修改True为False,是为了正常显示负号
  3. 第二行和第三行是为了使用微软雅黑作为默认字体

删除缓存

使用下面的代码,获取缓存文件夹.

import matplotlib
print(matplotlib.get_cachedir())

我的输出为

C:\Users\adobe\.matplotlib

所以,一般在用户目录的matplotlib,删除该目录下的所有文件

 
image.png


重启Python即可(意思是关闭所有正在运行的Python窗口,然后重新打开,要不然无法生效)

 

测试

使用如下的简单代码进行测试

# coding:utf-8
import matplotlib.pyplot as plt
plt.plot((1,2,3),(4,3,-1))
plt.xlabel(u'横坐标') # python3 可以不用u,已经是默认了
plt.ylabel(u'纵坐标')
plt.show()

 

 

 

posted on 2019-10-15 19:19  trp  阅读(722)  评论(0编辑  收藏  举报

导航