解决jupyter中matplotlib中文乱码问题

方法一:

第一步:系统中文字体查看

[hadoop@p168 ~]$ fc-list :lang=zh

/System/Library/Fonts/STHeiti Medium.ttc: 黑体-简,黑體-簡,Heiti SC,黒体-簡,Heiti-간체:style=中等,中黑,Medium,Halbfett,Normaali,Moyen,Medio,ミディアム,중간체,Médio,Средний,Normal,Media
/System/Library/Fonts/PingFang.ttc: 苹方-繁,蘋方-繁,PingFang TC:style=常规体,標準體,Regular
/System/Library/Fonts/PingFang.ttc: 苹方-简,蘋方-簡,PingFang SC:style=常规体,標準體,Regular
/System/Library/Fonts/PingFang.ttc: 苹方-港,蘋方-港,PingFang HK:style=常规体,標準體,Regular
/System/Library/Fonts/STHeiti Light.ttc: 黑体-繁,黑體-繁,Heiti TC,黒体-繁,Heiti-번체:style=细体,細體,Mager,Fein,Light,Ohut,Fin,Leggero,ライト,가는체,Licht,Tynn,Leve,Светлый,Fina
/System/Library/Fonts/PingFang.ttc: .苹方-简,.蘋方-簡,.PingFang SC:style=中黑体,中黑體,Medium
/System/Library/Fonts/PingFang.ttc: .苹方-港,.蘋方-港,.PingFang HK:style=中黑体,中黑體,Medium
/System/Library/Fonts/PingFang.ttc: .苹方-简,.蘋方-簡,.PingFang SC:style=中粗体,中粗體,Semibold
/System/Library/Fonts/PingFang.ttc: .苹方-港,.蘋方-港,.PingFang HK:style=中粗体,中粗體,Semibold
/System/Library/Fonts/PingFang.ttc: .苹方-繁,.蘋方-繁,.PingFang TC:style=中黑体,中黑體,Medium
/System/Library/Fonts/PingFang.ttc: .苹方-繁,.蘋方-繁,.PingFang TC:style=常规体,標準體,Regular
/System/Library/Fonts/PingFang.ttc: .苹方-繁,.蘋方-繁,.PingFang TC:style=中粗体,中粗體,Semibold
/System/Library/Fonts/PingFang.ttc: .苹方-简,.蘋方-簡,.PingFang SC:style=常规体,標準體,Regular
/System/Library/Fonts/PingFang.ttc: .苹方-港,.蘋方-港,.PingFang HK:style=常规体,標準體,Regular
/System/Library/Fonts/PingFang.ttc: 苹方-繁,蘋方-繁,PingFang TC:style=极细体,極細體,Ultralight

第二步:在代码中指定字体配


#coding:utf-8
import matplotlib
from matplotlib.font_manager import *
import matplotlib.pyplot as plt
myfont = FontProperties(fname='/System/Library/Fonts/PingFang.ttc')
matplotlib.rcParams['axes.unicode_minus']=False

方法二:

下载微软雅黑字体simhei.ttf拷贝到/home/hadoop/.pyenv/versions/2.7.10/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/ttf(文件路径参考1.c,根据实际情况修改)目录中,
然后删除~/.cache/matplotlib的缓冲目录
第三在代码中动态设置参数:

#coding:utf-8  
import matplotlib  
matplotlib.use('qt4agg')  
#指定默认字体  
matplotlib.rcParams['font.sans-serif'] = ['SimHei']   
matplotlib.rcParams['font.family']='sans-serif'  
#解决负号'-'显示为方块的问题  
matplotlib.rcParams['axes.unicode_minus'] = False   
plt.plot([-1,2,-5,3])  
plt.title(u'中文',fontproperties=myfont)  
plt.show()

方法三:

  1. 查找matplotlib路径
import matplotlib
matplotlib.matplotlib_fname()

输出路径大致如下,记住,第2步会使用:

xxx/matplotlib/mpl-data/matplotlibrc

  1. 安装SimHei字体
    字体链接 密码:5vn4

字体放到xxx/matplotlib/mpl-data/ttf下即可

  1. 修改配置文件
    vim 打开xxx/matplotlib/matplotlibrc,添加内容如下:
    在这里插入图片描述

4.删除缓存
rm ~/.cache/matplotlib -fr
重启notebook

猜你喜欢

转载自blog.csdn.net/tonydz0523/article/details/85260252