Ubuntu系统上使用python 的 matplotlib库展示和中文相关的信息时,往往无法显示,出现乱码.

原因是,缺乏对中文字体库的支持.

1. 解决方案

两种中文字体(Ubuntu):

[1] - 微软雅黑字体msyh.ttf:http://siwei.me/system/resources/W1siZiIsIjIwMTYvMDcvMTIvMDdfNTdfMjNfMTM5X21zeWgudHRmIl1d/msyh.ttf

[2] - 黑体 SimHei字体:https://www.lanzous.com/b870841/ (密码:65ic)

使用方法

[1] - 查看 matplotlib 字体的安装位置:

locate -b '\mpl-data'

一般路径,如:/usr/local/lib/python3.7/dist-packages/matplotlib/mpl-data/fonts/ttf/

[2] - 把下载的字体放到该目录下:

sudo mv msyh.ttf /usr/local/lib/python3.7/dist-packages/matplotlib/mpl-data/fonts/ttf/
sudo mv simhei.ttf /usr/local/lib/python3.7/dist-packages/matplotlib/mpl-data/fonts/ttf/

[3] - 删除当前用户 matplotlib 的缓冲文件.

cd ~/.cache/matplotlib
rm -rf *.*

注:matplotlib缓存文件一般在~/.cache/matplotlib. 也可以查看缓冲文件位置:

import matplotlib
print(matplotlib.get_cachedir())

[4] - matplotlib 使用指定字体:

import matplotlib.pyplot as plt

plt.rcParams[u'font.sans-serif'] = ['SimHei']
#或
plt.rcParams['font.family'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

或者:

https://blog.csdn.net/daixiangzi/article/details/88741712

from matplotlib import pyplot as plt
import matplotlib
import numpy as np
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import matplotlib.font_manager as fm
myfont = fm.FontProperties(fname='/usr/local/lib/python3.7/dist-packages/matplotlib/mpl-data/fonts/ttf/simhei.ttf')
data = np.random.randn(1000)
plt.hist(data,bins=40,density=0,facecolor="blue",edgecolor="black",alpha=0.7)
plt.xlabel("区间",fontproperties=myfont)
plt.ylabel("频率",fontproperties=myfont)
plt.title("直方图",fontproperties=myfont)
plt.show()

2. 相关

[1] - Python - 图片上显示中文字符 - AIUAI

Last modification:February 18th, 2020 at 11:52 am