Try   HackMD

Matplotlib 中文標籤問題

作者:王一哲
日期:2020/3/2

這篇只能算是按照網路上找到的方法,在自己的電腦上測試的筆記,主要參考以下兩篇文章:

  1. 解决Python使用matplotlib绘图时出现的中文乱码问题
  2. PYTHON 如何在Win 10解決matplotlib中文顯示的問題?

Windows 10

如果電腦裡有安裝中易宋體 (SimSun) 或是 中易黑體 (SimHei),可以按照第一篇文章的作法,直接在程式碼裡設定

plt.rcParams['font.sans-serif']=['SimSun']
plt.rcParams['axes.unicode_minus']=False

或是

plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False

但如果沒有安裝對應的字體,則要按照第二篇文章的作法,先安裝思源宋體,這是下載字體的連結。再到下列的檔案裡找到對應的字體名稱

C:\Users\[使用者名稱]\.matplotlib\fontlist-v310.json

例如我使用的是 NotoSansCJKtc 系列的字體,名稱是 Noto Sans CJK TC。以下是我試著使用中文標籤的程式碼,測試的環境為 Windows 10 家用版、Python 3.7.5、matplotlib 3.1.1。

import numpy as np # 引入科學計算函式庫 import matplotlib.pyplot as plt # 引入繪圖函式庫 plt.rcParams['font.sans-serif']=['Noto Sans CJK TC'] # 將字體設定為思源宋體 plt.rcParams['axes.unicode_minus']=False # 用來正常顯示負號 xmin, xmax, num = 0, 4*np.pi, 100 # 設定繪圖範圍、取點數 x = np.linspace(xmin, xmax, num) # 產生x, sin, cos, tan sin = np.sin(x) cos = np.cos(x) tan = np.tan(x) plt.figure(figsize=(6, 4.5), dpi=100) # 設定圖片尺寸 plt.title('三角函數圖形', fontsize=16) # 設定圖片標題 plt.xlabel(r'$\theta~\mathrm{(rad)}$', fontsize=14) # 設定坐標軸標籤 plt.ylabel('三角函數值', fontsize=14) plt.xticks(fontsize=12) # 設定坐標軸數字格式 plt.yticks(fontsize=12) plt.grid(color='gray', linestyle='--', linewidth=1) # 設定格線顏色、種類、寬度 plt.ylim(-2, 2) # 設定y軸繪圖範圍 # 繪圖並設定線條顏色、寬度、圖例 line1, = plt.plot(x, sin, color='red', linewidth=3, label='正弦 sin') line2, = plt.plot(x, cos, color='green', linewidth=3, label='餘弦 cos') line3, = plt.plot(x, tan, color='blue', linewidth=3, label='正切 tan') plt.legend(handles = [line1, line2, line3], loc='upper right') plt.savefig('TrigonometricFunction.svg') # 儲存圖片 plt.savefig('TrigonometricFunction.png') plt.show() # 顯示圖片

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
於 Windows 10 測試結果

Linux

測試的環境為 Lubuntu 19.10、Python 3.7.5、matplotlib 3.1.3。方法同上,先將下載回來的字體複製到以下的資料夾中

/home/[使用者名稱]/.local/lib/python3.7/site-packages/matplotlib/mpl-data/fonts/ttf/

再移除以下的檔案

/home/[使用者名稱]/.cache/matplotlib/fontlist-v310.json

如果擔心會出問題,可以先複製一份,如果失敗了再將檔案蓋回去就好。開啟 Python IDLE,執行前面的程式碼,可以畫出同樣的圖形,測試成功。

Image Not Showing Possible Reasons
  • The image file may be corrupted
  • The server hosting the image is unavailable
  • The image path is incorrect
  • The image format is not supported
Learn More →
於 Lubuntu 19.10 測試結果


tags:Python