Matplotlib - 字型索引



在 Matplotlib 庫中,字型索引指的是訪問和利用可用於渲染繪圖中文字元素的不同字型或字型的過程。Matplotlib 庫提供了對各種字型的訪問,瞭解字型索引涉及瞭解如何透過其名稱或索引使用這些字型。當我們想要使用不在預設集合中的字型或需要使用系統特定的字型時,這一點尤其重要。

Matplotlib 中的 font.family 引數接受表示已知字體系列的字串或表示特定字型索引的整數。數字索引用於引用在 Matplotlib 庫中註冊的字型。

Matplotlib 中的字型索引

以下是 matplotlib 庫中的字型索引方法。

字體系列

  • Matplotlib 庫提供了幾個字體系列,例如 'serif'、'sans-serif'、'monospace' 等。

  • 這些字體系列具有其獨特的特徵,用於定義字型的總體設計。

字型名稱

  • Matplotlib 庫允許使用特定的字型名稱來訪問系統上可用的特定字型。

  • 字型名稱能夠選擇自定義或已安裝的字型來渲染繪圖中的文字。

按名稱訪問字型

要訪問 Matplotlib 中的字型,我們可以使用字型名稱及其索引(如果可用)。

字型名稱

我們可以使用字型名稱訪問 matplotlib 中可用的字型。以下是使用 plt.rcParams['font.family'] 方法訪問 'Times New Roman' 字型的示例。

示例

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Times New Roman'
# Creating a data
x = [i for i in range(10,40)]
y = [i for i in range(30,60)]
# Creating a plot
plt.scatter(x,y,color = 'blue')
plt.xlabel('X-axis cube values')
plt.ylabel('Y-axis cube values')
plt.title('Title with Times New Roman Font')
plt.show()
輸出
Times New Roman

系統上的可用字型

Matplotlib 庫還可以使用系統上的可用字型。可用的字型可能因作業系統(如 Windows、macOS、Linux)以及已安裝的字型庫而異。

使用 findSystemFonts() 索引字型

Matplotlib 提供了一個名為 matplotlib.font_manager.findSystemFonts() 的函式,該函式返回系統上可用字型的路徑列表。

示例

在此示例中,我們使用 matplotlib.font_manager.findSystemFonts() 函式獲取所需的字型名稱索引列表。

import matplotlib.font_manager as fm
# Get a list of available fonts
font_list = fm.findSystemFonts()

# Display the first five fonts path
print("The first five fonts path:",font_list[:5])
輸出
The first five fonts path: ['C:\\Windows\\Fonts\\gadugi.ttf', 'C:\\WINDOWS\\Fonts\\COPRGTB.TTF', 'C:\\WINDOWS\\Fonts\\KUNSTLER.TTF', 'C:\\Windows\\Fonts\\OLDENGL.TTF', 'C:\\Windows\\Fonts\\taileb.ttf']

按索引訪問字型

字型索引涉及瞭解系統上可用字型的名稱或路徑。我們可以透過其名稱、別名或檔案路徑來引用這些字型,以在 Matplotlib 繪圖中設定字體系列,確保將所需的字型用於文字元素。

示例

在此示例中,我們使用字型路徑從系統訪問字型。

import matplotlib as mpl
import matplotlib.font_manager as fm
plt.rcParams['font.family'] = 'C:\Windows\Fonts\Comicz.ttf'

# Creating a data
x = [i for i in range(10,40)]
y = [i for i in range(30,60)]

# Creating a plot
plt.plot(x,y,color = 'violet')
plt.xlabel('X-axis cube values')
plt.ylabel('Y-axis cube values')
plt.title("The plot fonts with font indexing")
plt.show()

輸出

Font Indexing

注意

  • 字型索引和可用性可能會因 Matplotlib 庫中使用的後端而異。

  • 使用索引自定義字型可能是特定於後端的,或者需要特殊的配置,例如 LaTeX 渲染。

廣告