電腦環(huán)境:Windows7-64bit武学,Anaconda3-4.2.0(對(duì)應(yīng)python 3.5.2版本),IDE是Anaconda自帶的Spyder 3伦意。
1火窒、找到Windows系統(tǒng)自帶的字體庫(kù)目錄,默認(rèn)在C:\Windows\Fonts目錄下驮肉。
2熏矿、選擇你自己喜歡的字體,然后“右鍵”→“屬性”离钝,可以看到該字體的名字票编。
本教程以微軟雅黑字體為例,您也可以選擇其他字體卵渴,如果自帶的字體庫(kù)滿足不了您的需求栏妖,您可以網(wǎng)上下載其他字體,將字體解壓到C:\Windows\Fonts目錄即可奖恰。
3吊趾、在IDE工具中,導(dǎo)入matplotlib庫(kù)瑟啃,開始定義字體所在路徑论泛。
- 1 先不設(shè)置參數(shù),可以看到中文字體顯示為方框(此處使用的是SVC三分類模型)蛹屿。
- 2 設(shè)置參數(shù)之后屁奏,可以看到中文字體可以正常顯示了。(代碼經(jīng)過測(cè)試错负,可放心使用)
哪里需要中文設(shè)置坟瓢,保證該函數(shù)里有fontproperties = my_font參數(shù)即可。比如x軸的標(biāo)簽為:鳶尾花的花萼長(zhǎng)度犹撒。那么可以使用:
plt.xlabel('鳶尾花的花萼長(zhǎng)度', fontproperties = my_font)
# coding:utf-8
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
# 以下兩行是解決常見的其他問題
plt.rcParams['font.sans-serif'] = ['SimHei'] # 指定默認(rèn)字體
plt.rcParams['axes.unicode_minus'] = False # 解決保存圖像是負(fù)號(hào)'-'顯示為方塊的問題
import matplotlib.font_manager as mf # 導(dǎo)入字體管理器
my_font= mf.FontProperties(fname='C:\\Windows\\Fonts\\msyh.ttf') # 加載字體
iris = datasets.load_iris()
X = iris.data[:, :2]
Y = iris.target
def my_kernel(X, Y):
M = np.array([[2, 0], [0, 1.0]])
return np.dot(np.dot(X, M), Y.T)
h = 0.02
clf = svm.SVC(kernel = my_kernel)
clf.fit(X, Y)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)
plt.scatter(X[:, 0], X[:, 1], c=Y, cmap=plt.cm.Paired)
plt.title('測(cè)試U哿!识颊!3-Class classification using SVM with custom kernel',
fontproperties = my_font)
plt.axis('tight')
plt.show()