matplotlib之多边形选区(PolygonSelector)的使用


Posted in Python onFebruary 24, 2021

多边形选区概述

多边形选区是一种常见的对象选择方式,在一个子图中,单击鼠标左键即构建一个多边形的端点,最后一个端点与第一个端点重合即完成多边形选区,选区即为多个端点构成的多边形。在matplotlib中的多边形选区属于部件(widgets),matplotlib中的部件都是中性(neutral )的,即与具体后端实现无关。

多边形选区具体实现定义为matplotlib.widgets.PolygonSelector类,继承关系为:Widget->AxesWidget->_SelectorWidget->PolygonSelector。

PolygonSelector类的签名为class matplotlib.widgets.PolygonSelector(ax, onselect, useblit=False, lineprops=None, markerprops=None, vertex_select_radius=15)

PolygonSelector类构造函数的参数为:

  • ax:多边形选区生效的子图,类型为matplotlib.axes.Axes的实例。
  • onselect:多边形选区完成后执行的回调函数,函数签名为def onselect( vertices),vertices数据类型为列表,列表元素格式为(xdata,ydata)元组。
  • drawtype:多边形选区的外观,取值范围为{"box", "line", "none"},"box"为多边形框,"line"为多边形选区对角线,"none"无外观,类型为字符串,默认值为"box"。
  • lineprops:多边形选区线条的属性,默认值为dict(color='k', linestyle='-', linewidth=2, alpha=0.5)。
  • markerprops:多边形选区端点的属性,默认值为dict(marker='o', markersize=7, mec='k', mfc='k', alpha=0.5)。
  • vertex_select_radius:多边形端点的选择半径,浮点数,默认值为15,用于端点选择或者多边形闭合。

PolygonSelector类中的state_modifier_keys公有变量 state_modifier_keys定义了操作快捷键,类型为字典。

  • “move_all”: 移动已存在的选区,默认为"shift"。
  • “clear”:清除现有选区,默认为 "escape",即esc键。
  • “move_vertex”:正方形选区,默认为"control"。

PolygonSelector类中的verts特性返回多边形选区中的多有端点,类型为列表,元素为(x,y)元组,即端点的坐标元组。

案例

官方案例,https://matplotlib.org/gallery/widgets/polygon_selector_demo.html

案例说明

matplotlib之多边形选区(PolygonSelector)的使用

单击鼠标左键创建端点,最终点击初始端点闭合多边形,形成多边形选区。选区外的数据元素颜色变淡,选区内数据颜色保持不变。

按esc键取消选区。按shift键鼠标可以移动多边形选区位置,按ctrl键鼠标可以移动多边形选区某个端点的位置。退出程序时,控制台输出选区内数据元素的坐标。

控制台输出:

Selected points:
[[2.0 2.0]
 [1.0 3.0]
 [2.0 3.0]]

案例代码

import numpy as np

from matplotlib.widgets import PolygonSelector
from matplotlib.path import Path


class SelectFromCollection:
  """
  Select indices from a matplotlib collection using `PolygonSelector`.

  Selected indices are saved in the `ind` attribute. This tool fades out the
  points that are not part of the selection (i.e., reduces their alpha
  values). If your collection has alpha < 1, this tool will permanently
  alter the alpha values.

  Note that this tool selects collection objects based on their *origins*
  (i.e., `offsets`).

  Parameters
  ----------
  ax : `~matplotlib.axes.Axes`
    Axes to interact with.
  collection : `matplotlib.collections.Collection` subclass
    Collection you want to select from.
  alpha_other : 0 <= float <= 1
    To highlight a selection, this tool sets all selected points to an
    alpha value of 1 and non-selected points to *alpha_other*.
  """

  def __init__(self, ax, collection, alpha_other=0.3):
    self.canvas = ax.figure.canvas
    self.collection = collection
    self.alpha_other = alpha_other

    self.xys = collection.get_offsets()
    self.Npts = len(self.xys)

    # Ensure that we have separate colors for each object
    self.fc = collection.get_facecolors()
    if len(self.fc) == 0:
      raise ValueError('Collection must have a facecolor')
    elif len(self.fc) == 1:
      self.fc = np.tile(self.fc, (self.Npts, 1))

    self.poly = PolygonSelector(ax, self.onselect)
    self.ind = []

  def onselect(self, verts):
    path = Path(verts)
    self.ind = np.nonzero(path.contains_points(self.xys))[0]
    self.fc[:, -1] = self.alpha_other
    self.fc[self.ind, -1] = 1
    self.collection.set_facecolors(self.fc)
    self.canvas.draw_idle()

  def disconnect(self):
    self.poly.disconnect_events()
    self.fc[:, -1] = 1
    self.collection.set_facecolors(self.fc)
    self.canvas.draw_idle()


if __name__ == '__main__':
  import matplotlib.pyplot as plt

  fig, ax = plt.subplots()
  grid_size = 5
  grid_x = np.tile(np.arange(grid_size), grid_size)
  grid_y = np.repeat(np.arange(grid_size), grid_size)
  pts = ax.scatter(grid_x, grid_y)

  selector = SelectFromCollection(ax, pts)

  print("Select points in the figure by enclosing them within a polygon.")
  print("Press the 'esc' key to start a new polygon.")
  print("Try holding the 'shift' key to move all of the vertices.")
  print("Try holding the 'ctrl' key to move a single vertex.")

  plt.show()

  selector.disconnect()

  # After figure is closed print the coordinates of the selected points
  print('\nSelected points:')
  print(selector.xys[selector.ind])

到此这篇关于matplotlib之多边形选区(PolygonSelector)的使用的文章就介绍到这了,更多相关matplotlib 多边形选区内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
python 获取et和excel的版本号
Apr 09 Python
Python实现windows下模拟按键和鼠标点击的方法
Mar 13 Python
在Python程序中操作文件之flush()方法的使用教程
May 24 Python
python文件的md5加密方法
Apr 06 Python
基于python内置函数与匿名函数详解
Jan 09 Python
Python内置模块ConfigParser实现配置读写功能的方法
Feb 12 Python
PyQt5每天必学之事件与信号
Apr 20 Python
python画柱状图--不同颜色并显示数值的方法
Dec 13 Python
python实现K近邻回归,采用等权重和不等权重的方法
Jan 23 Python
Python 使用 Pillow 模块给图片添加文字水印的方法
Aug 30 Python
关于python中的xpath解析定位
Mar 06 Python
Jupyter notebook如何修改平台字体
May 13 Python
matplotlib部件之套索Lasso的使用
Feb 24 #Python
matplotlib之属性组合包(cycler)的使用
Feb 24 #Python
matplotlib bar()实现百分比堆积柱状图
Feb 24 #Python
matplotlib bar()实现多组数据并列柱状图通用简便创建方法
Feb 24 #Python
pandas apply使用多列计算生成新的列实现示例
Feb 24 #Python
pandas map(),apply(),applymap()区别解析
Feb 24 #Python
Python的Tqdm模块实现进度条配置
Feb 24 #Python
You might like
PHP中的加密功能
2006/10/09 PHP
php Sql Server连接失败问题及解决办法
2009/08/07 PHP
PHP内核探索:变量概述
2014/01/30 PHP
$()JS小技巧
2007/07/21 Javascript
为JavaScript提供睡眠功能(sleep) 自编译JS引擎
2010/08/16 Javascript
利用原生JS自动生成文章标题树的实例
2016/08/22 Javascript
JS实现的自动打字效果示例
2017/03/10 Javascript
JS正则验证多个邮箱完整实例【邮箱用分号隔开】
2017/04/19 Javascript
Angular+Node生成随机数的方法
2017/06/16 Javascript
angular select 默认值设置方法
2017/06/23 Javascript
vue实现移动端图片裁剪上传功能
2020/08/18 Javascript
实现图片首尾平滑轮播(JS原生方法—节流)
2017/10/17 Javascript
BootStrap table实现表格行拖拽效果
2018/12/01 Javascript
vue实现点击隐藏与显示实例分享
2019/02/13 Javascript
JavaScript仿京东秒杀倒计时
2020/03/17 Javascript
[13:38]2015国际邀请赛中国战队出征仪式
2015/05/29 DOTA
分析在Python中何种情况下需要使用断言
2015/04/01 Python
PyQt5每天必学之事件与信号
2018/04/20 Python
python 用opencv调用训练好的模型进行识别的方法
2018/12/07 Python
python 文本单词提取和词频统计的实例
2018/12/22 Python
python制作抖音代码舞
2019/04/07 Python
基于Python打造账号共享浏览器功能
2019/05/30 Python
python数组循环处理方法
2019/08/26 Python
Python获取、格式化当前时间日期的方法
2020/02/10 Python
Python txt文件常用读写操作代码实例
2020/08/03 Python
python import 上级目录的导入
2020/11/03 Python
让IE6支持css3,让 IE7、IE8 都支持CSS3
2011/10/09 HTML / CSS
俄罗斯领先的移动和数字设备在线商店:Svyaznoy.ru
2020/12/21 全球购物
未婚证明书模板
2014/10/08 职场文书
2014年语文教学工作总结
2014/12/17 职场文书
感谢信格式范文
2015/01/22 职场文书
自主招生英文自荐信
2015/03/25 职场文书
《詹天佑》教学反思
2016/02/20 职场文书
浅谈JS的二进制家族
2021/05/09 Javascript
CSS+HTML 实现顶部导航栏功能
2021/08/30 HTML / CSS
python编程实现清理微信重复缓存文件
2021/11/01 Python