【Matplotlib】中文显示问题

中文显示问题

本地Mac上作图,可以方便地实现中文字体显示。比如在Jupter中,通过:

方法一:不下载字体库即可实现中文显示 (MAC)

plt.rcParams['font.family']=['Arial Unicode MS']

方法二:下载指定字体训即可实现中文显示

plt.rcParams['font.sans-serif'] = 'SimHei'

该方法需确保SimHei.ttf字体文件存在于:anaconda3/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf

对于Linux系运行python代码的画图脚本,则需要一些额外的配置。在此记录详细过程及细节提示,以供后续参考。

1.若安装字体:

复制代码
# Matplotlib中设置字体-黑体,解决Matplotlib中文乱码问题
# 解决Matplotlib坐标轴负号'-'显示为方块的问题

plt.rcParams['font.sans-serif']=['SimHei']  
plt.rcParams['axes.unicode_minus']=False    

另外seaborn

复制代码
sns.set(font='SimHei')  # Seaborn中设置字体-黑体,解决Seaborn中文乱码问题
  1. 若未安装字体
    a.下载simhei.tff
    b.查看位置

    import matplotlib
    print(matplotlib.matplotlib_fname())
    /Users/bayes/anaconda3/envs/Env_3.6/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
    cp ./simhei.ttf /Users/bayes/anaconda3/envs/Env_3.6/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf

c.修改配置

复制代码
vi /Users/bayes/anaconda3/envs/Env_3.6/lib/python3.6/site-packages/matplotlib/mpl-data/matplotlibrc
font.family         : sans-serif
#去掉前面的#
font.sans-serif     : SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
#去掉前面的#,并在冒号后面添加SimHei
axes.unicode_minus  : False
#去掉前面的#,并将True改为False

d.缓存位置

复制代码
matplotlib.get_cachedir()
'/Users/bayes/.matplotlib'
rm -rf /Users/bayes/.matplotlib

e.重启

3.各种字体大小

复制代码
import matplotlib.pyplot as plt
SMALL_SIZE = 8
MEDIUM_SIZE = 10
BIGGER_SIZE = 12
plt.rc('font', size=SMALL_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=SMALL_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=MEDIUM_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=SMALL_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIGGER_SIZE)  # fontsize of the figure title