Python: matplotlib繪圖區自定義中英文字型以及部分設定
對於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: objectA 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()
效果:
- 錯誤排查:
- 互動視窗開啟、內聯影象視窗開啟
%matplotlib qt5 # iPython以互動視窗開啟matplotlib
%matplotlib inline # 以內聯靜態視窗繪製matplotlib
- 影象無法匯出pdf\eps,顯示
Truetype font is missing table
好像更新ipython和matplotlib最新版本能夠解決。如果不能解決可能只能直接plt.savefig('${File_Name}.pdf')
來儲存。
findfont: Font family [ xxx ] not found. Falling back to DejaVu Sans.
參考此文→→ findfont: Font family [ msyh ] not found. Falling back to DejaVu Sans.
參考資料:
- [1] matplotlib-中文字型設定
- [2] matplotlib-入門--font
- [3] jupyter-lab用matplotlib畫圖實現互動展示
- [4] 魔獸世界字型合併/補全工具 1.0.0
- [5] python matplotlib 畫圖小技巧: 自定義字型
- [6] 用Python的matplotlib畫圖,怎麼保證xlabel中中文用宋體,英文用新羅馬?
- [7] 中文變小框框?深入剖析matplotlib的字型邏輯
- [8] python matplotlib 中文顯示引數設定
- [9] 【python學習】-matplotlib圖形設定(線寬、標籤、顏色、圖框、線型別、圖例大小位置、圖框大小及畫素等)
- [10] 【Python基礎】matplotlib字型設定看這一篇就夠了
- [11] Matplotlib 3.5.1 documentation官方文件