Matplotlib - 圖表



在 Matplotlib 庫中,圖表是頂級容器,它包含繪圖或視覺化中的所有元素。可以將其視為建立繪圖的視窗或畫布。單個圖表可以包含多個子圖,即座標軸、標題、標籤、圖例和其他元素。Matplotlib 中的 **figure()** 函式用於建立一個新圖表。

語法

以下是 figure() 方法的語法和引數。

plt.figure(figsize=(width, height), dpi=resolution)

其中,

  • **figsize=(width, height)** − 指定圖表的寬度和高度(英寸)。此引數是可選的。

  • **dpi=resolution** − 設定圖表的每英寸點數(解析度)。可選,預設為 100。

建立圖表

要使用 **figure()** 方法建立圖表,我們必須將圖表大小和解析度值作為輸入引數傳遞。

示例

import matplotlib.pyplot as plt
# Create a figure
plt.figure(figsize=(3,3), dpi=100)
plt.show()

輸出

Figure size 300x300 with 0 Axes

向圖表新增繪圖

建立圖表後,我們可以使用 Matplotlib 中的各種 **plot()** 或 **subplot()** 函式在該圖表中新增繪圖或子圖(座標軸)。

示例

import matplotlib.pyplot as plt
# Create a figure
plt.figure(figsize=(3, 3), dpi=100)
x = [12,4,56,77]
y = [23,5,7,21]
plt.plot(x,y)
plt.show()

輸出

Adding plot

顯示和自定義圖表

要顯示和自定義圖表,我們有函式 **plt.show(), plt.title(), plt.xlabel(), plt.ylabel(), plt.legend()**。

plt.show()

此函式顯示包含所有已新增繪圖和元素的圖表。

自定義

我們可以執行自定義操作,例如使用 **plt.title(), plt.xlabel(), plt.ylabel(), plt.legend()** 等函式向圖表新增標題、標籤、圖例和其他元素。

示例

在這個例子中,我們使用 pyplot 模組的 **figure()** 方法,將 **figsize** 設定為 **(8,6)**,**dpi** 設定為 **100**,建立一個包含線形圖的圖表,幷包含標題、標籤和圖例等自定義選項。圖表可以包含多個繪圖或子圖,允許在一個視窗中進行復雜的視覺化。

import matplotlib.pyplot as plt
# Data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Create a figure
plt.figure(figsize=(8, 6), dpi=100)

# Add a line plot to the figure
plt.plot(x, y, label='Line Plot')

# Customize the plot
plt.title('Figure with Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()

# Display the figure
plt.show()
輸出
Figure

示例

這是另一個使用 **pyplot** 模組的 **figure()** 方法建立子圖的示例。

import matplotlib.pyplot as plt
# Create a figure
plt.figure(figsize=(8, 6))

# Add plots or subplots within the figure
plt.plot([1, 2, 3], [2, 4, 6], label='Line 1')
plt.scatter([1, 2, 3], [3, 5, 7], label='Points')

# Customize the figure
plt.title('Example Figure')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.legend()

# Display the figure
plt.show()
輸出
Subplot
廣告