Matplotlib - Axes 類



在 Matplotlib 的上下文中,axes並非指軸的複數形式。相反,它代表圖形或畫布上的整個繪圖區域。其中包括 x 軸、y 軸、繪圖資料、刻度、刻度標籤等等。

請參考下圖:

Axes_Class_intro

考慮一個圖形,其中使用 ax = fig.subplots() 方法建立了兩個 Axes 物件。第一個 axes 顯示指數資料,而第二個 axes 顯示正弦波。每個 Axes(子圖)都有自己的一組標籤、刻度和圖例,在同一圖形中提供不同的表示。

Matplotlib 中的 Axes 類

Axes() 類是建立資料視覺化的入口。一旦在圖形上例項化了一個 Axes 物件,就可以使用各種方法在該繪圖區域中新增和操作資料。

此類是matplotlib.axes模組的一部分,提供使用 Matplotlib 面向物件程式設計 (OOP) 介面工作的基本功能。大多數重要的繪圖方法都在 Axes 類中定義,使其成為自定義和增強視覺化的核心元件。

建立 Axes

建立 Axes 物件通常是 Matplotlib 繪圖的第一步。這可以透過 Figure 物件上的方法(如Figure.subplots()Figure.add_axes())或透過 pyplot 介面函式pyplot.subplots()來完成。這些方法可以建立一個或多個 Axes 物件。

示例

以下示例使用pyplot.subplot()方法在一個圖形上建立兩個 axes。subplots() 方法用於生成 axes 例項。

import matplotlib.pyplot as plt
import numpy as np

# Creating a 1x2 subplot layout
fig, (axes1, axes2)  = plt.subplots(1, 2, figsize=(7, 4),
   layout="constrained")

# Adding labels to each subplot
axes1.annotate('axes1', (0.5, 0.5),transform=axes1.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

axes2.annotate('axes2', (0.5, 0.5),transform=axes2.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

fig.suptitle('Creating Two Axes on a Figure')

# Displaying the plot
plt.show()

輸出

執行上述程式碼後,將得到以下輸出:

axes_class_ex1

更改 Axes 屬性

要設定 axes 的屬性,必須訪問 axes 物件,然後可以使用各種 `set_*` 方法來修改其屬性。

示例

import matplotlib.pyplot as plt
import numpy as np

# Creating a 1x2 subplot layout
fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4),
   constrained_layout=True)

# Changing the properties of the first axes
axes1.set_xlabel("X-axis")        # Set label for X-axis
axes1.set_ylabel("Y-axis")        # Set label for Y-axis
axes1.set_facecolor('lightgreen') # Setting background color
axes1.annotate('axes1', (0.5, 0.5), transform=axes1.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')
axes2.set_title('Second axes')
axes2.annotate('axes2', (0.5, 0.5), transform=axes2.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

# Adding a title to the figure
fig.suptitle('Changing Axes Properties')

# Displaying the plot
plt.show()

輸出

執行上述程式碼後,將得到以下輸出:

axes_class_ex4

在 Axes 上繪圖

此類提供了幾種高階繪圖方法,用於在 axes 上建立不同的圖。

示例

以下示例使用Axes.plot()方法建立一個表示 sin(x) 的線圖。

import matplotlib.pyplot as plt
import numpy as np

# Sample Data
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x**2)

# Create subplots
fig, axs = plt.subplots(figsize=(7,4))

# Draw the plot
axs.plot(x, y)

# Show the plot
plt.show()

輸出

執行上述程式碼後,將得到以下輸出:

axes_class_ex2

自定義 axes 資料

Axes 物件包含大部分圖形元素,例如 Axis、Tick、Line2D、Text、Polygon 等,並設定座標系。可以透過新增標籤、標題、圖例和註釋來自定義這些元素,從而提高視覺化的清晰度。

示例

這是一個簡單的示例,它向 Axes 新增標籤、標題和圖例。

import matplotlib.pyplot as plt
import numpy as np

# Sample Data
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x**2)

# Create subplots
fig, axs = plt.subplots(figsize=(7,4))

# Draw the plot
axs.plot(x, y, label='Sin(x)')

# Add titles
axs.set_title('Sin Plot')

# Add X and Y labels
axs.set_xlabel('X-axis')
axs.set_ylabel('Y-axis')

# Add legend
axs.legend()

# Show the plot
plt.show()

輸出

執行上述程式碼後,將得到以下輸出:

axes_class_ex3

清除 Axes

要清除 axes 的內容,可以使用axes.cla()axes.clear()方法。

示例

以下示例演示如何在子圖中清除第一個 axes。

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.linspace(-1, 1, 10)
y = np.exp(x)

# Creating subplots
fig, (axes1, axes2) = plt.subplots(1, 2, figsize=(7, 4),
   constrained_layout=True)

# Plotting on the first axes
axes1.plot(x, y, c='red')
axes1.set_xlabel("X-axis")        # Set label for X-axis
axes1.set_ylabel("Y-axis")        # Set label for Y-axis
axes1.set_facecolor('lightgreen') # Setting background color
axes1.annotate('axes1', (0.5, 0.5), transform=axes1.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

# Adding a title to the second axes
axes2.set_title('Second axes')
axes2.annotate('axes2', (0.5, 0.5), transform=axes2.transAxes,
   ha='center', va='center', fontsize=18,
   color='darkgrey')

# Clearing the first axes
axes1.cla()

# Adding a title to the figure
fig.suptitle('Clearing the Axes')

# Displaying the plot
plt.show()

輸出

執行上述程式碼後,將得到以下輸出:

axes_class_ex5
廣告