Matplotlib - 風格表



什麼是樣式表?

在 Matplotlib 庫中,樣式表是預定義的一組美學配置,用於控制繪圖的整體外觀。它們提供了一種便捷的方式,只需最少的努力即可更改繪圖的外觀和感覺。

樣式表包含對繪圖各種元素的預定義設定,例如顏色、線型、字型、網格樣式等等。Matplotlib 提供了一組內建樣式表,使我們能夠快速將不同的視覺主題應用於我們的繪圖。

當沒有設定特定樣式時,將使用預設樣式,但 Matplotlib 包括其他幾種樣式,例如 **gplot、seaborn、bmh、dark_background** 等等。這些樣式表提供了不同的配色方案、線型、字型設定和整體美學。

Matplotlib 提供了各種內建樣式表。以下是關於如何使用它們概述:

檢視可用的樣式表

Matplotlib 提供不同的樣式表,這些樣式表會改變繪圖的整體外觀,並更改顏色、線型、字型大小等元素。樣式表提供了一種快速簡便的方法來更改視覺化的美學。

語法

我們可以使用以下語法檢查可用的樣式表。

plt.style.available

示例

在這個例子中,我們使用 **plt.style.available** 獲取 Matplotlib 庫中所有可用的樣式表。

import matplotlib.pyplot as plt
# List available stylesheets
print("Available stylesheets:", plt.style.available)

輸出

Available stylesheets: [
   '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']

使用樣式表

使用 Matplotlib 樣式表非常簡單。我們可以將特定樣式應用於我們的繪圖。以下是語法。

語法

plt.style.use('stylesheet_name')

其中:

  • **plt.style.use()** - 用於將定義的樣式表應用於整個繪圖。

  • **stylesheet_name** - 我們想要應用的樣式表的名稱。

示例

在這個例子中,我們透過在建立繪圖之前使用 **plt.style.use('ggplot')** 來使用 **'ggplot'** 樣式表。

import matplotlib.pyplot as plt
# Using a specific stylesheet
plt.style.use('ggplot')  # Example: Using the 'ggplot' style
x = [10,30,20,50]
y = [30,23,45,10]
plt.plot(x,y)
plt.title("Plot with ggplot style sheet")
plt.show()

輸出

Using Stylesheet

臨時應用樣式表

如果我們想將樣式表臨時應用於特定程式碼塊而不影響其他繪圖,我們可以使用 **plt.style.context('stylesheet_name')**。

此臨時上下文僅在 `with` 語句下縮排的程式碼塊內應用指定的樣式。

示例

在這個例子中,我們使用 Matplotlib 庫中可用的 plt.style.context() 函式將樣式表設定為 **seaborn-dark**。

import matplotlib.pyplot as plt
x = [10,30,20,50]
y = [30,23,45,10]
with plt.style.context('seaborn-dark'):
   # Code for a plot with 'seaborn-dark' style
   plt.plot(x, y)
   plt.title('Seaborn-Dark Style')
   plt.show()  # The 'seaborn-dark' style will only affect this plot

輸出

Temporary Stylesheet

建立自定義樣式表

我們還可以透過定義 **.mplstyle** 檔案或使用指定樣式引數的 Python 字典來建立自定義樣式表:

示例

在這個例子中,我們使用字典建立自定義樣式表。

import matplotlib.pyplot as plt
# Define a custom style using a dictionary
custom_style = {
   'lines.linewidth': 10,
   'lines.color': 'red',
   'axes.labelsize': 30,
   # Add more style configurations as needed
}
# Use the custom style
plt.style.use(custom_style)
x = [10,30,20,50]
y = [30,23,45,10]
plt.plot(x,y)
plt.title("Plot with custom style sheet")
plt.show()

輸出

Custom Stylesheet

樣式表提供了一種有效的方法來維護多個繪圖之間的一致性,或者輕鬆地試驗各種視覺樣式。我們可以選擇最符合我們的偏好或資料視覺化特定要求的樣式表。

廣告