Matplotlib 简明教程

Matplotlib - Pick Event

在计算机编程中, click event 指的是用户与屏幕上的元素交互的事件,通常是通过选择或点击该元素。该事件在用户的输入设备(例如鼠标或触摸屏)与图形表示中的对象交互时触发。

Pick Event in Matplotlib

当用户在靠近被指定为可拾取的艺术家的画布上选择一个位置时,在 matplotlib 中会出现拾取事件,使用 Artist.set_picker 。该事件提供了一种对用户的操作(例如点击绘图中的点、矩形或文本)进行交互式响应的方式。

Enabling the Pick Event

可以通过设置 Line2D、Text、Patch、Polygon、AxesImage 等艺术家的“拾取器”属性来启用对象的拾取能力。该属性确定艺术家是否会根据用户的交互触发拾取事件。“拾取器”属性可用的选项如下:

  1. None − 禁用拾取,这是默认行为。

  2. bool − 如果为真,则启用拾取,并且鼠标事件在其上方时,艺术家会触发拾取事件。

  3. function − 用户提供的一个函数,用来确定鼠标事件是否击中了艺术家。该函数应返回 hit, props = picker(artist, mouseevent)。

为艺术家启用拾取后,您需要使用 fig.canvas.mpl_connect('pick_event', callback_function) 方法连接到画布,以在按鼠标事件接收拾取回调。

Picking the Points, Rectangles, and Text

在绘图中,可以选择特定元素,比如点、矩形和文本。这允许用户单击这些元素并触发自定义操作。

Example

以下示例展示了选择绘图中的点、矩形和文本以便获取所选对象的属性。

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

Picking on a Scatter Plot

选择散点图涉及选择由标记表示的各个点。散点图通常用来显示两个变量之间的关系。启用散点图上的选择功能允许用户互动识别和响应特定数据点。

Example

此示例展示了选择散点图,其中散点由 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

Images Picking

使用 Axes.imshow 绘制的图像也可以进行选择。

Example

在此示例中,选择在使用 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

Legend Picking

Matplotlib 允许选择图例项,提供了一种交互绘图中的图例元素的方式。用户可以单击图例项以切换相应绘图元素的可见性。

Example

以下是一个演示如何启用图例选择的示例。

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