Matplotlib - 樣式



什麼是 Matplotlib 中的樣式?

在 Matplotlib 庫中,樣式是允許我們輕鬆更改繪圖視覺外觀的配置。它們充當預定義的美學選擇集,透過更改顏色、線條樣式、字型、網格線等方面來實現。這些樣式有助於快速自定義繪圖的外觀和感覺,而無需每次都手動調整各個元素。

我們可以嘗試不同的樣式,以找到最適合我們的資料或視覺偏好的樣式。樣式提供了一種快速有效的方法來增強 Matplotlib 庫中繪圖的視覺呈現。

內建樣式

Matplotlib 帶有多種內建樣式,它們提供不同的配色方案、線條樣式、字型大小和其他視覺屬性。

例如:ggplot、seaborn、classic、dark_background 等。

更改樣式

使用 plt.style.use('style_name') 將特定樣式應用於我們的繪圖。

Matplotlib 樣式的關鍵方面

  • 預定義樣式 - Matplotlib 庫帶有各種內建樣式,為我們的繪圖提供不同的美學效果。

  • 易用性 - 透過應用樣式,我們可以立即更改繪圖的整體外觀,以匹配不同的主題或視覺偏好。

  • 一致性 - 樣式確保在同一樣式設定下的多個繪圖或圖形之間的一致性。

使用樣式

在 matlplotlib 庫中使用可用樣式涉及幾個步驟。讓我們一一看看它們。

設定樣式

為了設定所需的樣式,我們必須使用 plt.style.use('style_name') 在建立繪圖之前設定特定的樣式。

例如,如果我們想要設定 ggplot 樣式,我們必須使用以下程式碼。

import matplotlib.pyplot as plt
plt.style.use('ggplot')  # Setting the 'ggplot' style

可用樣式

我們可以使用 plt.style.available 檢視可用樣式的列表。

示例

import matplotlib.pyplot as plt
print(plt.style.available)  # Prints available styles

輸出

['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background', 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn', 'seaborn-bright', 'seaborn-colorblind', 'seaborn-dark', 'seaborn-dark-palette', 'seaborn-darkgrid', 'seaborn-deep', 'seaborn-muted', 'seaborn-notebook', 'seaborn-paper', 'seaborn-pastel', 'seaborn-poster', 'seaborn-talk', 'seaborn-ticks', 'seaborn-white', 'seaborn-whitegrid', 'tableau-colorblind10']

應用自定義樣式

我們可以建立包含特定配置的自定義樣式檔案,然後使用 plt.style.use('path_to_custom_style_file') 應用它們。

應用 seaborn-darkgrid 樣式

在此示例中,樣式 'seaborn-darkgrid' 應用於繪圖,從而改變其外觀。

示例

import matplotlib.pyplot as plt
# Using a specific style
plt.style.use('seaborn-darkgrid')

# Creating a sample plot
plt.plot([1, 2, 3, 4], [10, 15, 25, 30])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sample Plot')
plt.show()
輸出
Dark Grid

應用 ggplot 樣式

在此示例中,我們對繪圖使用 ggplot 樣式。

示例

import matplotlib.pyplot as plt
# Using a specific style
plt.style.use('seaborn-white')

# Creating a sample plot
plt.plot([1, 2, 3, 4], [10, 15, 25, 30])
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Sample Plot')
plt.show()
輸出
White Grid
廣告