2017年12月19日 星期二

Jupyter notebook 操作(9) --- Matplotlib 繪圖中文字無法正常顯示問題

用 Python 中 Matplotlib 繪圖最頭痛的就是加入中文顯示,由於 Matplotlib 函式庫沒有支援中文字型,所以要在圖中呈現中文字說明或註解等,中文字就會變成了一個個小方框,造成無法處理中文的顯示。

為了要顯示中文字,可用以下三種方法來處理:
方法一:修改Matplotlib畫圖設定。
在 Command line上尋找matplotlibrc設定檔位址。
python -c "print __import__('matplotlib').matplotlib_fname()"

或是在Jupyter上尋找matplotlibrc設定檔位址。
import matplotlib
print(matplotlib.matplotlib_fname())

開啟matplotlibrc設定檔,找到開頭為 #font.serif、#font.sans-serif 這兩行。

移除 #,在 "DejaVu Serif" 前加入 "SimHei,"

並找到 #axes.unicode_minus 這行,移除 #,與設定為 False,日圖片中可以顯示負號。

修改後,請將 Jupyter 重新啟動,讓 matplotlibrc 設定可以生效。

程式碼如下:
%pylab inline
x = linspace(-5, 5, 2000)
plot(x, sinc(x))
plt.gcf().set_size_inches(20, 8)
plt.title(u'sinc(x)圖形', fontsize=25)
plt.xlabel(u'-5到5範圍', fontsize=25)
plt.ylabel(u'sinc(x)', fontsize=25)
plt.tick_params(axis ='both', labelsize=25)
plt.savefig('sample.jpg')

查看系統支援的字型
fm = matplotlib.font_manager.FontManager()
for f in fm.ttflist:
    print f.name.decode('utf-8')

方法二:外部動態指定字型1。
透過 rcParams 指定外部字型方式顯示中文,其實指定 rcParams 就是動態修改 matplotlibrc 設定檔。
plt.rcParams['font.sans-serif'] = 'simhei'
plt.rcParams['axes.unicode_minus'] = False
程式碼如下:
%pylab inline
x = linspace(-5, 5, 2000)
plt.rcParams['font.sans-serif'] = 'simhei'
plt.rcParams['axes.unicode_minus'] = False
plot(x, sinc(x))
plt.gcf().set_size_inches(20, 8)
plt.title(u'sinc(x)圖形', fontsize=25)
plt.xlabel(u'-5到5範圍', fontsize=25)
plt.ylabel(u'sinc(x)', fontsize=25)
plt.tick_params(axis ='both', labelsize=25)
plt.savefig('sample.jpg')

方法三:外部動態指定字型2。
直接指定 C:\Windows\Fonts 字型,設定中文顯示。
import matplotlib.font_manager as fm
font = fm.FontProperties(fname='C:\Windows\Fonts\simhei.ttf', size=25)
程式碼如下:
%pylab inline
import matplotlib.font_manager as fm

font = fm.FontProperties(fname='C:\Windows\Fonts\simhei.ttf', size=25)
x = linspace(-5, 5, 2000)
plot(x, sinc(x))
plt.gcf().set_size_inches(20, 8)
plt.title(u'sinc(x)圖形', fontproperties = font)
plt.xlabel(u'-5到5範圍', fontproperties = font)
plt.ylabel(u'sinc(x)', fontproperties = font)
plt.tick_params(axis ='both', labelsize=25)
plt.savefig('sample.jpg')

字型名稱找尋,到 C:\WINDOWS\Fonts 下,找到需要的字型,滑鼠右鍵點選內容,找到字型名稱。

參考資料: