Matplotlib - 多游標



簡介

Matplotlib 沒有專門的多游標小部件。但是,Matplotlib 提供了游標小部件,可用於向繪圖新增游標,以顯示特定位置的資訊。此外,matplotlib.widgets 模組提供了一個名為MultiCursor 的工具,允許我們在單個繪圖中使用多個游標線。這對於比較 x 軸上不同點的值很有用。

讓我們探討如何在 Matplotlib 中使用 MultiCursor 工具以及游標小部件,並討論其功能、實現和潛在用例。

MultiCursor 的功能

以下是 Multicursor 小部件的功能。

多個游標 - Matplotlib 中的MultiCursor 工具允許我們在單個繪圖中新增多個游標線。每個游標線對應一組特定的軸。

游標之間的協調 - 游標是連結的,即當與其中一個互動時,它們會一起移動。這有助於輕鬆比較不同軸上的資料點。

可自定義的外觀 - 可以根據我們的偏好自定義游標的外觀,例如線條顏色和線型。

動態資料顯示 - 當我們沿著 x 軸移動游標時,透過提供即時資訊,動態顯示游標位置處的相應 y 值。

基本游標示例

這是一個演示游標類用法的基本示例。

示例

import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
import numpy as np
# Generating sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Creating a plot
fig, ax = plt.subplots()
line, = ax.plot(x, y, label='Sine Wave')
# Adding a cursor to the plot
cursor = Cursor(ax, horizOn=True, vertOn=True, useblit=True, color='red', linewidth=1)
# Displaying the plot
plt.show()

輸出

Basic Multicursor

使用 mplcursors 實現多游標

要在 Matplotlib 中實現多游標,我們可以使用mplcursors 包,它提供了額外的游標功能。我們可以使用以下程式碼行安裝mplcursors 包。

示例

pip install mplcursors

輸出

Collecting mplcursors
   Downloading mplcursors-0.5.3.tar.gz (88 kB)
      -------------------------------------- 88.8/88.8 kB 557.3 kB/s eta 0:00:00
   Installing build dependencies: started
   Installing build dependencies: finished with status 'done'
   Getting requirements to build wheel: started
   Getting requirements to build wheel: finished with status 'done'
   Installing backend dependencies: started
   Installing backend dependencies: finished with status 'done'
   Preparing metadata (pyproject.toml): started
   Preparing metadata (pyproject.toml): finished with status 'done'

mplcursors 的用法

現在讓我們探索一個使用mplcursors 在 Matplotlib 中建立多游標的示例。

示例

import matplotlib.pyplot as plt
import mplcursors
import numpy as np
# Generate sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
# Create subplots
fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(8, 6))
# Plot data on the first subplot
ax1.plot(x, y1, label='Sin(x)')
ax1.set_ylabel('Amplitude')
ax1.legend()
# Plot data on the second subplot
ax2.plot(x, y2, label='Cos(x)')
ax2.set_xlabel('x')
ax2.set_ylabel('Amplitude')
ax2.legend()
# Enable multicursor on both subplots
mplcursors.cursor(hover=True, multiple=True)
# Display the plot
plt.show()

輸出

Using MPL Cursor

擴充套件到多游標

要將此概念擴充套件到真正多游標的場景(其中多個游標獨立移動),我們需要為每條線或資料來源建立游標類的單獨例項,並相應地更新資訊。

多游標的用例

以下是多游標小部件使用用例。

比較分析 - 多游標在比較不同繪圖之間的對應資料點時非常有用,這有助於視覺化關係。

時間序列探索 - 對於時間序列資料,多游標允許同時檢查多個時間序列中特定時間點處的數值。

互動式資料探索 - 多游標透過允許使用者探索不同維度的資料點來增強資料視覺化的互動性。

相關性分析 - 在研究兩個或多個變數之間的相關性時,多游標有助於識別模式和相關性。

廣告