不用下載字型解決Mac系統下Python的matplotlib庫中文亂碼的問題
百度或谷歌matplotlib庫繪圖時產生中文亂碼問題,得到的最多的答案就是下面幾行程式碼:
import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['SimHei']
很明顯,這是因為mac下沒有SimHei字型庫,於是大多數教程都叫你怎麼下載SimHei字型怎麼放到mac的字型庫,以及配置matplotlib的字型庫,可是這些教程大都是幾年前的,有的已經失效,有的則過於複雜。
於是...為什麼要費這些功夫呢,直接找找mac底下有哪些支援中文的字型庫不就好了嘛...然後我還真找到了Arial Unicode MS
,親測可用,程式碼如下:
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS']
不信你可以用下面的完整的繪圖程式碼試試看:
測試程式碼
import numpy as np import matplotlib.pyplot as plt plt.rcParams['font.sans-serif'] = ['Arial Unicode MS'] plt.figure() names = ['5', '10', '15', '20', '25'] x = range(len(names)) y = [0.855, 0.84, 0.835, 0.815, 0.81] y1=[0.86,0.85,0.853,0.849,0.83] plt.plot(x, y, marker='o', mec='r', mfc='w',label=u'y=x^2曲線圖') plt.plot(x, y1, marker='*', ms=10,label=u'y=x^3曲線圖') plt.legend()# 讓圖例生效 plt.xticks(x, names, rotation=45) plt.margins(0) plt.subplots_adjust(bottom=0.15) plt.xlabel(u"time(s)鄰居") #X軸標籤 plt.ylabel("RMSE") #Y軸標籤 plt.title("我就看看中文能不能用") #標題 plt.show()