解决matplotlib中文乱码问题(Ubuntu16.04)

来源:互联网 发布:jsp商城系统源码 编辑:程序博客网 时间:2024/05/19 23:55

网上教程很多,但是折腾了好久才弄好。特此记录一下。

  1. 查看matplotlib配置文件位置
>>> import matplotlib>>> print matplotlib.matplotlib_fname()/usr/local/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc

PS:因为之前安装了两个matplotlib的库。所以这里会有问题。
一个使用sudo apt-get install python-matplotlib安装,在root用户下。
一个使用pip install matplotlib普通用户安装。
后来使用 sudo apt-get remove python-matplotlib后,才能显示正常的matplotlib配置文件。

  1. 永久解决方法

    1. 首先将windwos中fonts目录下的simhei.ttf拷贝到/usr/share/matplotlib/mpl-data/fonts/ttf目录中
    2. 修改配置文件
      去除这三列之前的‘#’
      在font.sans-serif后添加,SimHei

      ```#font.family         : sans-serif        #font.sans-serif     : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif   ...#axes.unicode_minus : False #解决负号'-'显示为方块的问题```
    3. 删除~/.cache/matplotlib的缓冲
  2. 验证
    新建python文件,输入以下内容

# -*- coding:utf-8 -*-from matplotlib import pyplot as pltplt.title(u'显示中文')plt.show()

若出现如下图的中文字符,则说明更改成功。
这里写图片描述

最后附上simhei.ttf的链接
simhei.ttf

原创粉丝点击