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
广告