如何将matplotlib中全局的中文设置成宋体

来源:互联网 发布:小猪o2o源码下载 编辑:程序博客网 时间:2024/06/08 11:22

配置介绍:python 3.5 ;操作系统,windows 8.1 ;

步骤:

1、由于matplotlib默认不支持ttc,所以可以将ttc转换ttf先。将Windows字体 simsun.ttc上传到 https://transfonter.org/ttc-unpack 在线转换成TTF,
2、得到simsun.ttf和nsimsun.ttf,将两个ttf文件放到PYTHON安装目录的 Lib\site-packages\matplotlib\mpl-data\fonts\ttf 子目录下。

例如:我的电脑上,如下:C:\Users\vinsuan\AppData\Local\Programs\Python\Python35\Lib\site-packages\matplotlib\mpl-data\fonts\ttf
3、删除字体缓存以便重新生成字体缓存:清空$HOME/.matplotlib/文件夹下的所有文件及文件夹,如果不放心,请先备份!!!

例如:我的电脑上,如下:C:\Users\vinsuan\.matplotlib


代码示例:

#coding:utf-8import matplotlib.pyplot as pltimport numpy as npimport matplotlib as mplmpl.rcParams['font.family'] = 'sans-serif'mpl.rcParams['font.sans-serif'] = 'NSimSun,Times New Roman'//中文除外的设置成New Roman,中文设置成宋体x, y = np.loadtxt('data.txt', delimiter=',', unpack=True)plt.plot(x,y, '+',label='PoW算法',color='black')plt.xlabel('难度值')plt.ylabel('时间')plt.title('PoW共识的hash难题解决时间表')plt.legend()plt.show()

结果: