Matplotlib -拾取事件



在計算機程式設計中,**點選事件**指的是使用者與螢幕上某個元素進行互動時發生的事件,通常是透過選擇或點選該元素來觸發。當用戶的輸入裝置(如滑鼠或觸控式螢幕)與圖形表示中的物件進行互動時,就會觸發此事件。

Matplotlib中的拾取事件

Matplotlib中的拾取事件發生在使用者選擇畫布上靠近某個圖形物件的位置時,該圖形物件已使用**Artist.set_picker**指定為可拾取的。此事件提供了一種互動方式,可以對使用者的操作(例如點選繪圖中的點、矩形或文字)做出響應。

啟用拾取事件

可以透過設定圖形物件(如Line2D、Text、Patch、Polygon、AxesImage等)的“picker”屬性來啟用物件的拾取功能。此屬性決定了圖形物件是否可以根據使用者互動觸發拾取事件。“picker”屬性可用的選項有:

  • **None** - 停用拾取,這是預設行為。

  • **bool** - 如果為True,則啟用拾取,如果滑鼠事件位於圖形物件上,則該圖形物件會觸發拾取事件。

  • **function** - 使用者提供的函式,用於確定滑鼠事件是否命中圖形物件。該函式應返回hit, props = picker(artist, mouseevent)。

啟用圖形物件的拾取功能後,需要使用**fig.canvas.mpl_connect('pick_event', callback_function)**方法連線到圖形畫布,以便在滑鼠按下事件上接收拾取回調。

拾取點、矩形和文字

可以啟用對繪圖中特定元素(如點、矩形和文字)的拾取功能。這允許使用者點選這些元素並觸發自定義操作。

示例

以下示例演示了在繪圖中拾取點、矩形和文字,以獲取所拾取物件的屬性。

import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand

from matplotlib.lines import Line2D
from matplotlib.patches import Rectangle
from matplotlib.text import Text

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

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 7))
ax1.set_title('click on points, rectangles or text', picker=True)
ax1.set_xlabel('xlabel', picker=True, bbox=dict(facecolor='green'))
ax1.set_ylabel('ylabel', picker=True, bbox=dict(facecolor='red'))
line, = ax1.plot(rand(100), 'o', picker=True, pickradius=5)

# Pick the rectangle.
ax2.bar(range(10), rand(10), picker=True)
# Make the xtick labels pickable.
for label in ax2.get_xticklabels():  
   label.set_picker(True)

def onpick(event):
   if isinstance(event.artist, Line2D):
      thisline = event.artist
      xdata = thisline.get_xdata()
      ydata = thisline.get_ydata()
      ind = event.ind
      print('onpick line:', np.column_stack([xdata[ind], ydata[ind]]))
   elif isinstance(event.artist, Rectangle):
      patch = event.artist
      print('onpick patch:', patch.get_path())
   elif isinstance(event.artist, Text):
      text = event.artist
      print('onpick text:', text.get_text())

fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

輸出

執行上述程式後,您將獲得以下圖形,並點選任意點、矩形或文字以觀察此示例的工作原理:

pick_Event_ex1

以下是控制檯視窗中觀察到的屬性:

onpick line: [[45.          0.63297416]]
onpick text: xlabel
onpick text: ylabel
onpick patch: Path(array([[0., 0.],
   [1., 0.],
   [1., 1.],
   [0., 1.],
   [0., 0.]]), array([ 1,  2,  2,  2, 79], dtype=uint8))
onpick patch: Path(array([[0., 0.],
   [1., 0.],
   [1., 1.],
   [0., 1.],
   [0., 0.]]), array([ 1,  2,  2,  2, 79], dtype=uint8))
onpick line: [[85.          0.93665595]]
onpick text: click on points, rectangles or text
onpick text: 4

觀看下面的影片,瞭解此拾取事件功能的工作原理。

pick_Event_ex1 gif

在散點圖上拾取

在散點圖上拾取涉及選擇由標記表示的單個點。散點圖通常用於視覺化兩個變數之間的關係。在散點圖上啟用拾取允許使用者互動式地識別和響應特定的資料點。

示例

此示例演示了在散點圖上拾取,其中散點由PathCollection支援。

from numpy.random import rand
import matplotlib.pyplot as plt

# Generate sample data
x, y, c, s = rand(4, 100)

# Define a function to handle pick events on the scatter plot
def onpick3(event):
   ind = event.ind
   print('onpick3 scatter:', ind, x[ind], y[ind])

# Create a Matplotlib figure and axis
fig, ax = plt.subplots(figsize=(7, 4))
ax.set_title('Click on the points')

# Create a scatter plot
ax.scatter(x, y, 100*s, c, picker=True)

# Connect the pick event handler to the figure canvas
fig.canvas.mpl_connect('pick_event', onpick3)
plt.show()

輸出

執行上述程式後,您將獲得以下圖形,並點選任意點、矩形或文字以觀察此示例的工作原理:

pick_Event_ex2
onpick scatter: [25] [0.11699828] [0.53441235]
onpick scatter: [27 44] [0.24286321 0.24281114] [0.37273147 0.3410762 ]
onpick scatter: [86] [0.40636809] [0.44143683]
onpick scatter: [60] [0.38819555] [0.47496597]
onpick scatter: [51] [0.63094438] [0.57754482]
onpick scatter: [71] [0.27925334] [0.01716168]
onpick scatter: [72 94] [0.859042   0.86511669] [0.19949375 0.16885001]
onpick scatter: [37] [0.95150989] [0.11653306]

觀看下面的影片,瞭解此拾取事件功能的工作原理。

pick_Event_ex2 gif

影像拾取

使用Axes.imshow繪製的影像也可以設定為可拾取的。

示例

在此示例中,拾取功能演示在使用**Axes.imshow()**方法繪製的影像上。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.image import AxesImage

# Create a Matplotlib figure and axis
fig, ax = plt.subplots(figsize=(7, 4))

# Display the images
ax.imshow(np.random.rand(10, 5), extent=(1, 2, 1, 2), picker=True)
ax.imshow(np.random.rand(5, 10), extent=(3, 4, 1, 2), picker=True)
ax.imshow(np.random.rand(20, 25), extent=(1, 2, 3, 4), picker=True)
ax.imshow(np.random.rand(30, 12), extent=(3, 4, 3, 4), picker=True)
ax.set(xlim=(0, 5), ylim=(0, 5))

# Define a function to handle pick events
def onpick(event):
   artist = event.artist
   if isinstance(artist, AxesImage):
      im = artist
      A = im.get_array()
      print('onpick image', A.shape)

# Connect the pick event handler to the figure canvas
fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

輸出

執行上述程式後,您將獲得以下圖形,並點選任意點、矩形或文字以觀察此示例的工作原理:

pick_Event_ex3
onpick image (20, 25)
onpick image (30, 12)
onpick image (10, 5)
onpick image (5, 10)
onpick image (5, 10)

觀看下面的影片,瞭解此拾取事件功能的工作原理。

pick_Event_ex3 gif

圖例拾取

Matplotlib允許在圖例項上進行拾取,提供了一種與繪圖中圖例元素進行互動的方法。使用者可以點選圖例條目以切換相應繪圖元素的可見性。

示例

這是一個演示如何啟用圖例拾取的示例。

import numpy as np
import matplotlib.pyplot as plt

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

# Create a Matplotlib figure and axis
fig, ax = plt.subplots(figsize=(7, 4))
ax.set_title('Click on legend line to toggle line on/off')

# Plot two lines and create a legend
line1, = ax.plot(x, y1, label='Sin(x)')
line2, = ax.plot(x, y2, label='Cos(x)')
legend = ax.legend(fancybox=True, shadow=True)

lines = [line1, line2]
map_legend_to_ax = {}

pickradius = 5

# Enable picking on the legend
for legend_line, ax_line in zip(legend.get_lines(), lines):
   legend_line.set_picker(pickradius) 
   map_legend_to_ax[legend_line] = ax_line

# Define a function to handle pick events on the legend
def on_legend_pick(event):
   legend_line = event.artist

   # Do nothing if the source of the event is not a legend line.
   if legend_line not in map_legend_to_ax:
     return

   ax_line = map_legend_to_ax[legend_line]
   visible = not ax_line.get_visible()
   ax_line.set_visible(visible)
   # Change the alpha on the line in the legend, so we can see what lines
   # have been toggled.
   legend_line.set_alpha(1.0 if visible else 0.2)
   fig.canvas.draw()

# Connect the pick event handler to the figure canvas
fig.canvas.mpl_connect('pick_event', on_legend_pick)

# Works even if the legend is draggable.
legend.set_draggable(True)
plt.show()

輸出

執行上述程式後,您將獲得以下圖形,並點選任意點、矩形或文字以觀察此示例的工作原理:

pick_Event_ex4

觀看下面的影片,瞭解此拾取事件功能的工作原理。

pick_Event_ex4 gif
廣告

© . All rights reserved.