Matplotlib - 縮放視窗



在資料視覺化/繪圖中,縮放視窗是指調整檢視以使特定物件或區域更大或更小的過程。此互動式功能在探索圖形、圖表或任何視覺表示時特別有用,使使用者能夠專注於感興趣的特定區域或全面檢視整個內容。

Matplotlib 中的縮放視窗

Matplotlib 的關鍵功能之一是其對事件處理的支援,它允許使用者將滑鼠點選等事件連線到繪圖中的特定操作。在本教程中,我們將探索 Matplotlib 中的縮放視窗事件處理,重點關注button_press_event以及如何使用它來建立可縮放視窗。

示例 1

此示例建立兩個圖形(源和縮放)。源圖形顯示散點圖,縮放圖形顯示初始的放大檢視。當在源圖形中單擊一個點時,on_press函式透過使用button_press_event觸發。此 on_press 函式調整可縮放圖形的限制,以在所單擊的點為中心建立縮放效果。

import matplotlib.pyplot as plt
import numpy as np

# Fixing random state for reproducibility
np.random.seed(19601)

# Create source and zoomable figures and axes
figsrc, axsrc = plt.subplots(figsize=(3.7, 3.7))
figzoom, axzoom = plt.subplots(figsize=(3.7, 3.7))

# Set initial limits and titles for both axes
axsrc.set(xlim=(0, 1), ylim=(0, 1), autoscale_on=False, title='Click to zoom')
axzoom.set(xlim=(0.45, 0.55), ylim=(0.4, 0.6), autoscale_on=False, title='Zoom window')

# Generate random data for scatter plots
x, y, s, c = np.random.rand(4, 100)
s *= 200

# Plot the scatter plots on both axes
axsrc.scatter(x, y, s, c)
axzoom.scatter(x, y, s, c)

# Define the event handling function
def on_press(event):
   if event.button != 1:
      return
   x, y = event.xdata, event.ydata
   axzoom.set_xlim(x - 0.1, x + 0.1)
   axzoom.set_ylim(y - 0.1, y + 0.1)
   figzoom.canvas.draw()

# Connect the event handler to the source figure
figsrc.canvas.mpl_connect('button_press_event', on_press)

# Show the plots
plt.show()

輸出

執行上述程式後,您將獲得以下輸出:

zoom_window_ex1

觀看下面的影片以觀察縮放視窗功能在此處的運作方式。

Zoom_Window gif

示例 2

讓我們再建立一個使用 Matplotlib 建立縮放視窗的示例。在此示例中,一個簡單的正弦波繪製在主軸上,並使用plt.axes()方法建立了一個較小的可縮放視窗。當您單擊主圖中的一個點時,on_press 函式將被觸發,調整縮放視窗的限制,以在所單擊的點為中心建立縮放效果。

import matplotlib.pyplot as plt
import numpy as np

# Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create a figure and axis
fig, ax = plt.subplots(figsize=(7, 4))
ax.plot(x, y, label='Sin(x)')
ax.set_title('Zoom Window Example')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend()

# Create a zoomable window
zoomed_ax = plt.axes([0.55, 0.25, 0.3, 0.3], facecolor='lightgoldenrodyellow')
zoomed_ax.plot(x, y, label='Sin(x)')
zoomed_ax.set_title('Zoomed Window')
zoomed_ax.set_xlim(2, 4)
zoomed_ax.set_ylim(0.5, 1)

def on_press(event):
   if event.button != 1:
      return
   x, y = event.xdata, event.ydata
   zoomed_ax.set_xlim(x - 1, x + 1)
   zoomed_ax.set_ylim(y - 0.2, y + 0.2)
   fig.canvas.draw()

# Connect the event handler to the figure
fig.canvas.mpl_connect('button_press_event', on_press)

plt.show()

輸出

執行上述程式後,您將獲得以下輸出:

zoom_window_ex2

觀看下面的影片以觀察縮放視窗功能在此處的運作方式。

zoom_window_ex2 gif
廣告