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创建只读属性对象的方法(ReadOnlyObject)
Feb 10 Python
python中文编码问题小结
Sep 28 Python
开源Web应用框架Django图文教程
Mar 09 Python
详解Python函数可变参数定义及其参数传递方式
Aug 02 Python
python监测当前联网状态并连接的实例
Dec 18 Python
Python控制键盘鼠标pynput的详细用法
Jan 28 Python
Django框架模板的使用方法示例
May 25 Python
Pandas_cum累积计算和rolling滚动计算的用法详解
Jul 04 Python
linux 下selenium chrome使用详解
Apr 02 Python
15个应该掌握的Jupyter Notebook使用技巧(小结)
Sep 23 Python
python 实现图片修复(可用于去水印)
Nov 19 Python
Pycharm在指定目录下生成文件和删除文件的实现
Dec 28 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/11/25 PHP
PHP中读写文件实现代码
2011/10/20 PHP
thinkphp中空模板与空模块的用法实例
2014/11/26 PHP
php基于curl实现的股票信息查询类实例
2016/11/11 PHP
laravel 实现关闭CSRF(全部关闭、部分关闭)
2019/10/21 PHP
推荐25个超炫的jQuery网格插件
2014/11/28 Javascript
javascript实现的图片切割多块效果实例
2015/05/07 Javascript
AngularJS中watch监听用法分析
2016/11/04 Javascript
微信公众平台开发教程(五)详解自定义菜单
2016/12/02 Javascript
微信小程序 页面跳转传值实现代码
2017/07/27 Javascript
jQuery Layer弹出层传值到父页面的实现代码
2017/08/17 jQuery
javascript实现Java中的Map对象功能的实例详解
2017/08/21 Javascript
禁止弹窗中蒙层底部页面跟随滚动的几种方法
2017/12/07 Javascript
详解在React里使用&quot;Vuex&quot;
2018/04/02 Javascript
JavaScript链式调用实例浅析
2018/12/19 Javascript
Node.js assert断言原理与用法分析
2019/01/04 Javascript
详解如何运行vue项目
2019/04/15 Javascript
Vue将页面导出为图片或者PDF
2020/08/17 Javascript
微信小程序开发技巧汇总
2019/07/15 Javascript
jQuery-Citys省市区三级菜单联动插件使用详解
2019/07/26 jQuery
Python基于pillow判断图片完整性的方法
2016/09/18 Python
Python利用BeautifulSoup解析Html的方法示例
2017/07/30 Python
python 字符串和整数的转换方法
2018/06/25 Python
对python条件表达式的四种实现方法小结
2019/01/30 Python
Django csrf 两种方法设置form的实例
2019/02/03 Python
Python增强赋值和共享引用注意事项小结
2019/05/28 Python
Opencv 图片的OCR识别的实战示例
2021/03/02 Python
Infababy英国:婴儿推车、Travel System婴儿车和婴儿汽车座椅销售
2018/05/23 全球购物
高级Java程序员面试题
2016/06/23 面试题
六十大寿答谢词
2014/01/12 职场文书
中专生毕业个人鉴定
2014/02/26 职场文书
民政局离婚协议书范本
2014/10/20 职场文书
心灵点滴观后感
2015/06/02 职场文书
PHP实现两种排课方式
2021/06/26 PHP
python如何为list实现find方法
2022/05/30 Python
table不让td文字溢出操作方法
2022/12/24 HTML / CSS