matplotlib部件之矩形选区(RectangleSelector)的实现

2022-07-24,,,

矩形选区概述

矩形选区是一种常见的对象选择方式,这个名词最常见于photoshop中,用于在一个子图选择鼠标拖动的矩形区域中的元素,在matplotlib中的矩形选区属于部件(widgets),matplotlib中的部件都是中性(neutral )的,即与具体后端实现无关。

矩形选区具体实现定义为matplotlib.widgets.rectangleselector类,继承关系为:widget->axeswidget->_selectorwidget->rectangleselector。

rectangleselector类的签名为class matplotlib.widgets.rectangleselector(ax, onselect, drawtype='box', minspanx=0, minspany=0, useblit=false, lineprops=none, rectprops=none, spancoords='data', button=none, maxdist=10, marker_props=none, interactive=false, state_modifier_keys=none)

rectangleselector类构造函数的参数为:

  • ax:矩形选区生效的子图,类型为matplotlib.axes.axes的实例。
  • onselect:矩形选区完成后执行的回调函数,函数签名为def onselect(eclick: mouseevent, erelease: mouseevent),eclick和erelease分别为开始和结束选区时的鼠标事件。
  • drawtype:矩形选区的外观,取值范围为{"box", "line", "none"},"box"为矩形框,"line"为矩形选区对角线,"none"无外观,类型为字符串,默认值为"box"。
  • lineprops:当drawtype == "line"时线条的属性,默认值为dict(color="black", linestyle="-", linewidth=2, alpha=0.5)。
  • rectprops:当drawtype == "box"时矩形框的属性,默认值为dict(facecolor="red", edgecolor="black", alpha=0.2, fill=true)。
  • button:设置可用于触发矩形选区的鼠标键,mousebutton列表,默认为所有鼠标键。
  • interactive:是否允许交互,布尔值,默认为false,即选择完成后选区即消失,值为true时,选区选择完成后不消失,除非按快捷键解除。
  • state_modifier_keys:快捷键设置,类型为字典。
    • “move”: 移动已存在的选区,默认没有修饰键。
    • “clear”:清除现有选区,默认为 "escape",即esc键。
    • “square”:正方形选区,默认为"shift"。
    • “center”:以当前点作为选区的中心点,默认为 "ctrl"。
    • “square” 和 “center” 可以组合使用。

案例

官方案例,

案例说明

拖动鼠标画出矩形选区,默认为交互模式,显示选区框,按esc键取消选区,控制台显示选区的坐标和使用的鼠标键。按t键切换矩形选区功能的激活状态,非激活状态矩形选区功能不生效。

控制台输出:

(0.74, -0.38) --> (8.90, 0.75)
 the buttons you used were: 1 1

代码分析

from matplotlib.widgets import rectangleselector
import numpy as np
import matplotlib.pyplot as plt

# 矩形选区选择时的回调函数
def line_select_callback(eclick, erelease):
  """
  callback for line selection.

  *eclick* and *erelease* are the press and release events.
  """
  x1, y1 = eclick.xdata, eclick.ydata
  x2, y2 = erelease.xdata, erelease.ydata
  print(f"({x1:3.2f}, {y1:3.2f}) --> ({x2:3.2f}, {y2:3.2f})")
  print(f" the buttons you used were: {eclick.button} {erelease.button}")

# 激活状态快捷键回调函数,active属性和set_active方法继承自_selectorwidget类
def toggle_selector(event):
  print(' key pressed.')
  if event.key == 't':
    if rs.active:
      print(' rectangleselector deactivated.')
      rs.set_active(false)
    else:
      print(' rectangleselector activated.')
      rs.set_active(true)

# 绘图
fig, ax = plt.subplots()
n = 100000 # if n is large one can see improvement by using blitting.
x = np.linspace(0, 10, n)

ax.plot(x, np.sin(2*np.pi*x)) # plot something
ax.set_title(
  "click and drag to draw a rectangle.\n"
  "press 't' to toggle the selector on and off.")

# 构造矩形选区实例,选取外观为矩形框,鼠标键为左键右键有效,允许保留选区
# drawtype is 'box' or 'line' or 'none'
rs = rectangleselector(ax, line_select_callback,
                    drawtype='box', useblit=true,
                    button=[1, 3], # disable middle button
                    minspanx=5, minspany=5,
                    spancoords='pixels',
                    interactive=true)
# 绑定键盘事件,实现切换矩形选区激活状态功能
fig.canvas.mpl_connect('key_press_event', toggle_selector)
plt.show()

到此这篇关于matplotlib部件之矩形选区(rectangleselector)的实现的文章就介绍到这了,更多相关matplotlib 矩形选区内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《matplotlib部件之矩形选区(RectangleSelector)的实现.doc》

下载本文的Word格式文档,以方便收藏与打印。