1. 程式人生 > 其它 >Python: matplotlib繪圖區自定義中英文字型以及部分設定

Python: matplotlib繪圖區自定義中英文字型以及部分設定

對於Python的新手,如果在matplotlib-pyplot繪圖區的輸出總是有比較強迫症美觀的自定義要求,本文為圖窗配置了自定義的中英文字型樣式,基於Jupyter記事本作為註記備忘。

對於matplotlib繪圖區總是有比較強迫症的自定義要求,對於剛剛接觸Python的新手來說,各種配置起來還是比較繁瑣,因此開一個帖子作為註記備忘。(Jupyter-Based)

  • 內建字型:

只能選擇同款字型,用預設英文字型無法顯示中文,用宋體的話中文能夠顯示但英文較醜。這裡採用rcParams全域性設定引數,也可使用font_manager.FontProperties()物件函式,參考matplotlib網頁原文設定如下。

class matplotlib.font_manager.FontProperties(family=None, style=None, variant=None, weight=None, stretch=None, size=None, fname=None, math_fontfamily=None)[source]


Bases: object

A class for storing and manipulating font properties.

The font properties are the six properties described in the W3C Cascading Style Sheet, Level 1 font specification and math_fontfamily for math fonts:

family: A list of font names in decreasing order of priority. The items may include a generic font family name, either 'sans-serif' (default), 'serif', 'cursive', 'fantasy', or'monospace'. In that case, the actual font to be used will be looked up from the associated rcParam.

style: Either 'normal' (default), 'italic' or 'oblique'.

variant: Either 'normal' (default) or 'small-caps'.

stretch: A numeric value in the range 0-1000 or one of 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed', 'normal' (default), 'semi-expanded', 'expanded', 'extra-expanded' or 'ultra-expanded'.

weight: A numeric value in the range 0-1000 or one of 'ultralight', 'light', 'normal' (default), 'regular', 'book', 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black'.

size: Either an relative value of 'xx-small', 'x-small', 'small', 'medium', 'large', 'x-large', 'xx-large' or an absolute font size, e.g., 10 (default).

math_fontfamily: The family of fonts used to render math text; overrides rcParams["mathtext.fontset"] (default: 'dejavusans'). Supported values are the same as the ones supported by rcParams["mathtext.fontset"] (default: 'dejavusans'): 'dejavusans', 'dejavuserif', 'cm', 'stix', 'stixsans' and 'custom'.

%matplotlib qt5 
#以互動視窗開啟matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager

config = {
    "font.family":'serif', # sans-serif/serif/cursive/fantasy/monospace
    "font.size": 20, # medium/large/small
    'font.style':'normal', # normal/italic/oblique
    'font.weight':'normal', # bold
    "mathtext.fontset":'cm',# 'cm' (Computer Modern)
    "font.serif": ['cmb10'], # 'Simsun'宋體
    "axes.unicode_minus": False,# 用來正常顯示負號
}
plt.rcParams.update(config)

x = np.linspace(0, 6, 50)
plt.plot(x, np.sin(x), label = r"Sine $\sin(\theta)$")
plt.title(r'Sine Function $\alpha_i \leq \beta_j$')
plt.xlabel(r'$\theta_i$')
plt.ylabel(r'$\sin\theta$')
plt.ion()
plt.show()

效果:

  • 自定義字型:

使用者希望自定義字型,即分別設定中文、英文、數學公式的字型,由於這裡採用字型融合的應用將中英文混合,通過匯入ttf檔案以滿足自定義配置的要求。(好看的圖片,流程比較繁瑣)

可以參考結合Github-字型合併/補全工具進行配置。

%matplotlib qt5 
# iPython以互動視窗開啟matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager

font_path = 'C:\\Users\\${User_Name}\\AppData\\Local\\Microsoft\\Windows\\Fonts\\${Font_Name}.ttf'  # 此處改為自己字型的路徑
font_manager.fontManager.addfont(font_path)
prop = font_manager.FontProperties(fname=font_path)

plt.rcParams['font.family'] = prop.get_name()
plt.rcParams['mathtext.fontset'] = 'cm'  # 'cm' (Computer Modern)

x = np.linspace(0, 6, 50)
plt.plot(x, np.sin(x), label = r"正弦函式 Sine $\sin(\theta)$")
plt.title(r'中文測試 Sine Function $\alpha_i \leq \beta_j$')
plt.xlabel(r'$\theta_i$')
plt.ylabel(r'$\sin\theta$')
plt.legend(fontsize = 'small', borderpad=1.5, labelspacing=0.2)
plt.ion()
# plt.savefig('sin.pdf')
plt.show()

效果:

  • 錯誤排查:
  1. 互動視窗開啟、內聯影象視窗開啟
%matplotlib qt5 # iPython以互動視窗開啟matplotlib
%matplotlib inline # 以內聯靜態視窗繪製matplotlib
  1. 影象無法匯出pdf\eps,顯示Truetype font is missing table

好像更新ipython和matplotlib最新版本能夠解決。如果不能解決可能只能直接plt.savefig('${File_Name}.pdf')來儲存。

  1. findfont: Font family [ xxx ] not found. Falling back to DejaVu Sans.

參考此文→→ findfont: Font family [ msyh ] not found. Falling back to DejaVu Sans.

參考資料: