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: 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.

參考資料:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM