Matplotlib - 滾動事件



通常,滾動事件發生在使用者與滑鼠滾輪互動時。滑鼠中間的滾輪用於在任何頁面上上下滾動,而無需使用文件或網頁右側的垂直捲軸。在本教程中,我們將探討 Matplotlib 中的滾動事件處理。

Matplotlib 中的滾動事件

Matplotlib 提供了一種透過MouseEvent類處理滾動事件的機制。當用戶滾動滑鼠滾輪時,會觸發此scroll_event事件。它用於為繪圖中的互動式導航或縮放提供機制。

示例

這是一個簡單的示例,它檢測滾動事件並根據使用者向上或向下滾動滑鼠滾輪顯示訊息。
import matplotlib.pyplot as plt
import numpy as np

def on_scroll(event):
   if event.button == 'up':
      print('Scroll Up Event Triggered..')
   elif event.button == 'down':
      print('Scroll Down Event Triggered..')

# Create a figure and axis
fig, ax = plt.subplots()
ax.text(0.13, 0.5, 'Scroll Mouse Wheel on me!', dict(size=20))

# Connect the on_scroll method to the scroll_event
fig.canvas.mpl_connect('scroll_event', on_scroll)

plt.show()

輸出

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

scroll_event_ex1
Scroll Up Event Triggered..
Scroll Up Event Triggered..
Scroll Down Event Triggered..
Scroll Up Event Triggered..
Scroll Down Event Triggered..
Scroll Up Event Triggered..
Scroll Up Event Triggered..

觀看下面的影片,觀察此滾動事件功能在此處的執行方式。

scroll_event_ex1 gif

使用滾動事件縮放

Matplotlib 中的滾動事件可用於動態縮放繪圖。透過將滾動事件連線到可呼叫函式,使用者可以動態調整繪圖內的檢視。

示例

讓我們看看一個演示如何使用滾動事件實現縮放功能的示例。

import matplotlib.pyplot as plt

def zoom_factory(axs, base_scale=2.):
   def zoom_fun(event):
      # get the current x and y limits
      cur_xlim = axs.get_xlim()
      cur_ylim = axs.get_ylim()
      cur_xrange = (cur_xlim[1] - cur_xlim[0]) * 0.2
      cur_yrange = (cur_ylim[1] - cur_ylim[0]) * 0.2

      # get event x location
      xdata = event.xdata  
      ydata = event.ydata  

      if event.button == 'up':
         # deal with zoom in
         scale_factor = 1/base_scale
      elif event.button == 'down':
         # deal with zoom out
         scale_factor = base_scale
      else:
         # deal with something that should never happen
         scale_factor = 1
         print(event.button)

      # set new limits
      axs.set_xlim([xdata - cur_xrange*scale_factor,
         xdata + cur_xrange*scale_factor])
      axs.set_ylim([ydata - cur_yrange*scale_factor,
         ydata + cur_yrange*scale_factor])

      # force re-draw
      plt.draw()  

   # get the figure of interest
   fig = axs.get_figure()  

   # Connect the call back function to the scroll_event
   fig.canvas.mpl_connect('scroll_event', zoom_fun)

   # return the function
   return zoom_fun

# Example Usage
fig, axs = plt.subplots(figsize=(7, 4))
axs.plot(range(100))
scale = 1.5
f = zoom_factory(axs, base_scale=scale)
plt.show()

輸出

執行上述程式後,您將獲得以下圖形,滾動滑鼠滾輪以觀察此繪圖中的縮放效果 -

scroll_event_ex2

觀看下面的影片,觀察此滾動事件功能在此處的執行方式。

scroll_event_ex2 gif

透過影像進行互動式滾動

Matplotlib 中的滾動事件還可以應用於互動式滾動一系列影像。當瀏覽多維資料集或影像集合時,此功能特別有用。

示例

此示例建立了一個 IndexTracker 類,以使用滾動事件瀏覽一系列 2D 切片。on_scroll 方法根據滾動方向調整索引,然後更新並顯示影像。

import matplotlib.pyplot as plt
import numpy as np

class IndexTracker:
   def __init__(self, axs, X):
      self.index = 0
      self.X = X
      self.axs = axs
      self.im = axs.imshow(self.X[:, :, self.index])
      self.update()

   def on_scrolling(self, event):
      print(event.button, event.step)
      increment = 1 if event.button == 'up' else -1
      maxs_index = self.X.shape[-1] - 1
      self.index = np.clip(self.index + increment, 0, maxs_index)
      self.update()

   def update(self):
      self.im.set_data(self.X[:, :, self.index])
      self.axs.set_title(
         f'Use scroll wheel to navigate\nindex {self.index}')
      self.im.axes.figure.canvas.draw()

# 3D data
x, y, z = np.ogrid[-25:25:100j, -25:25:100j, 1:50:100j]
X = np.sin(x * y * z) / (x * y * z)

# Create a figure
fig, axs = plt.subplots()
tracker = IndexTracker(axs, X)

fig.canvas.mpl_connect('scroll_event', tracker.on_scrolling)
plt.show()

輸出

執行上述程式後,您將獲得以下圖形,滾動滑鼠滾輪以觀察此示例的工作原理 -

scroll_event_ex3
up 1.0
up 2.0
down -1.0
down -2.0
down -1.0
up 1.0
up 1.0
down -1.0
down -1.0
up 1.0
up 3.0
down -1.0
down -3.0

觀看下面的影片,觀察此滾動事件功能在此處的執行方式。

scroll_event_ex3 gif
廣告