python的matplotlib默认情况下是不支持中文的,中文会显示为小方格,所以需要自己指定中文字体到画图中
下载中文字体
中文字体一推,随便用哪一个。我用的下面一个
http://fontzone.net/download/simhei
找到当前环境中matplotlib字体的安装位置
- 即是当前虚拟环境的位置
1
2
3
4
5locate -b '\mpl-data'
/root/.virtualenvs/py3scrapy/lib/python3.5/site-packages/matplotlib/mpl-data
/root/github/JobSpiders/virtualenv/py3scrapy/lib/python3.5/site-packages/matplotlib/mpl-data
/root/paper/virtualenv/py3scrapy/lib/python3.5/site-packages/matplotlib/mpl-data
/usr/share/matplotlib/mpl-data
我的里面有三个,第一个就是我当前所用的环境.
复制字体到/root/.virtualenvs/py3scrapy/lib/python3.5/site-packages/matplotlib/mpl-data/fonts/ttf 目录中
1
2
3cd ~/.cache/matplotlib ##clear cache
rm -rf *.*
## then restart jupyter notebook1
2
3
4import matplotlib as mpl
from matplotlib import pyplot as plt
mpl.rcParams[u'font.sans-serif'] = ['simhei']
mpl.rcParams['axes.unicode_minus'] = False也可以通过直接指定字体的位置
1
2
3
4
5
6
7import matplotlib.font_manager as mfm
import matplotlib.pyplot as plt
font_path = "/usr/share/fonts/custom/simhei.ttf"
prop = mfm.FontProperties(fname=font_path)
plt.text(0.5, 0.5, s=u'测试', fontproperties=prop')
plt.show()
参考链接
https://jdhao.github.io/2017/05/13/guide-on-how-to-use-chinese-with-matplotlib/
https://blog.csdn.net/jeff_liu_sky_/article/details/54023745
https://matplotlib.org/2.0.0/users/text_props.html
https://scentellegher.github.io/visualization/2018/05/02/custom-fonts-matplotlib.html