Matplotlib - 子圖示題



什麼是子圖示題?

在 Matplotlib 中,子圖示題是指分配給較大圖形中每個子圖的各個標題。當我們在網格中排列多個子圖(例如繪圖矩陣)時,通常有益於為每個子圖新增標題,以提供上下文或描述該特定子圖的內容。

在建立單個圖形中的多個視覺化效果時,設定子圖示題是一種有用的做法,因為它可以增強我們整體繪圖的可讀性和理解性。我們有名為set_title()的方法來設定子圖的標題。

透過利用set_title(),我們可以為圖形中的各個子圖新增描述性標題,從而更好地組織和理解複雜的視覺化效果。

子圖示題的用途

  • 提供上下文 - 子圖示題提供有關較大圖形中每個子圖內容的描述性資訊,有助於更好地理解視覺化效果。

  • 區分子圖 - 標題透過允許檢視者輕鬆識別和解釋每個子圖的資料或目的來幫助區分多個繪圖。

子圖示題的重要性

  • 子圖示題有助於闡明子圖網格中各個繪圖的內容或目的,尤其是在將多個視覺化效果一起呈現時。

  • 它們有助於快速識別每個子圖中呈現的資訊,從而提高視覺化效果的整體可解釋性。

語法

以下是設定子圖示題的語法和引數。

ax.set_title('Title')

其中,

  • ax - 它表示要設定標題的子圖的軸物件。

  • set_title() - 用於設定標題的方法。

  • 'Title' - 它是要設定標題的字串文字。

帶有標題的子圖

在這個示例中,我們正在建立子圖並透過使用 Matplotlib 庫中提供的set_title()方法為每個子圖設定標題。

示例

import matplotlib.pyplot as plt
import numpy as np

# Generating sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)

# Creating subplots
fig, (ax1, ax2) = plt.subplots(1, 2)

# Plotting on the first subplot
ax1.plot(x, y1)
ax1.set_title('Sine Wave')

# Plotting on the second subplot
ax2.plot(x, y2)
ax2.set_title('Cosine Wave')

# Displaying the subplots
plt.show()
輸出
Subtitles Plots

示例

在此示例中,我們正在建立子圖併為每個子圖新增標題。

import matplotlib.pyplot as plt
import numpy as np

# Generating sample data
x = np.linspace(0, 10, 50)
y = np.sin(x)

# Generating random data for scatter plot
np.random.seed(0)
x_scatter = np.random.rand(50) * 10
y_scatter = np.random.rand(50) * 2 - 1  # Random values between -1 and 1

# Creating subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))  # 1 row, 2 columns

# Line plot on the first subplot
ax1.plot(x, y, color='blue', label='Line Plot')
ax1.set_title('Line Plot')
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')
ax1.legend()

# Scatter plot on the second subplot
ax2.scatter(x_scatter, y_scatter, color='red', label='Scatter Plot')
ax2.set_title('Scatter Plot')
ax2.set_xlabel('X-axis')
ax2.set_ylabel('Y-axis')
ax2.legend()

# Displaying the subplots
plt.show()
輸出
Subplots Plots
廣告