centos下matplotlib 中文乱码

1、安装字体(需要TTF的文件格式,TTC的不行)

下载
http://font.chinaz.com/130130474870.htm
文件的命名可随便命名

2、获取环境路径

from matplotlib.font_manager import FontManager

import subprocess

import matplotlib

print matplotlib.matplotlib_fname()

fm = FontManager()

mat_fonts = set(f.name for f in fm.ttflist)

print mat_fonts

output = subprocess.check_output(

    'fc-list :lang=zh -f "%{family}\n"', shell=True)

print '*' * 10, 'avia', '*' * 10

print output

zh_fonts = set(f.split(',', 1)[0] for f in output.split('\n'))

available = mat_fonts & zh_fonts

print '*' * 10, 'avia', '*' * 10

for f in available:

    print f

3、将该字体拷贝入上面运行结果中的路径

需要TTF的文件格式,TTC的不行

~/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf

4、修改matplotlibrc

vim ~/anaconda2/lib/python2.7/site-packages/matplotlib/mpl-data/matplotlibrc

主要取消font.family 和font.sans-serif 的注释,并在font.sans-serif 中添加刚刚安装的字体 WenQuanYi Zen Hei Mono

font.family         : sans-serif
font.sans-serif     : WenQuanYi Zen Hei Mono, DejaVu Sans, Bitstream Vera Sans, Computer Modern Sans Serif, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif

5、删除缓存

rm -rf ~/.cache/matplotlib/

6、测试

# -*- coding: utf-8 -*-
"""
Created on Fri Jan 11 14:48:09 2019

@author: linpc
"""
import matplotlib
from matplotlib import pyplot as plt



font = {
    'family' : 'sans-serif',
    'weight' : 'bold',
    'size'   : 12
}
font1 = {
    'family' : 'sans-serif',
    'weight' : 'bold',
    'size'   : 12
}
matplotlib.rc('font', **font)

width = 5
height = 5

plt.figure(figsize=(width, height),facecolor='WHITE')
plt.title(u'测试',fontdict=font)
plt.legend(loc='best', shadow=True,fontsize=12)
plt.xlabel(u'测试',fontdict=font1)
plt.ylabel(u'测试',fontdict=font1)
plt.savefig("test.png")  
test.png

你可能感兴趣的:(centos下matplotlib 中文乱码)