1. 程式人生 > >如何將matplotlib中全域性的中文設定成宋體

如何將matplotlib中全域性的中文設定成宋體

配置介紹: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-8
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
mpl.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()

結果: