matplotlib之多边形选区(PolygonSelector)的使用
作者:mighty13 发布时间:2023-12-30 19:33:37
多边形选区概述
多边形选区是一种常见的对象选择方式,在一个子图中,单击鼠标左键即构建一个多边形的端点,最后一个端点与第一个端点重合即完成多边形选区,选区即为多个端点构成的多边形。在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
案例说明
单击鼠标左键创建端点,最终点击初始端点闭合多边形,形成多边形选区。选区外的数据元素颜色变淡,选区内数据颜色保持不变。
按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])
来源:https://blog.csdn.net/mighty13/article/details/113378808
猜你喜欢
- 先举个例子,以前负责教育培训类网站的时候,曾经接到过这样一个项目,需求方希望做一个充满趣味性的新手入门频道,页面要炫,最好是flash,用户
- 本文实例讲述了Thinkphp5.0 框架的请求方式与响应方式。分享给大家供大家参考,具体如下:Thinkphp5.0 的请求方式方法一(使
- 到了今天,数据库已经成了网站的灵魂,可以说,没有对数据进行集中管理就算不上是一个真正的网站。而ASP加数据库,更成了主流中的主流,网站里的用
- GIL(Global Interpreter Lock,即全局解释器锁)1.为什么有GIL设计者为了规避类似于内存管理这样的复杂的竞争风险问
- 本文实例讲述了Python实现获取前100组勾股数的方法。分享给大家供大家参考,具体如下:本来想采用穷举试探的方式来做这个算法,后来发现还是
- isalnum()方法检查判断字符串是否包含字母数字字符。语法以下是isalnum()方法的语法:str.isa1num()参数
- 1,filesize()函数返回错误的值。 使用curl将某个页面下载到本地时,需要将下载到的临时文件tmpHtml.txt的内容读取到一个
- 这里的内容以Linux进程基础和Linux文本流为基础。subprocess包主要功能是执行外部的命令和程序。比如说,我需要使用wget下载
- This application failed to start because it could not find or load the
- 在python中,向函数传递参数的类型有两种,一种是值传递,还有一种是引用传递,如果你恰恰好会一点c基础,你可以理解为前者为传递形参,而后者
- 前言shape函数是Numpy中的函数,它的功能是读取矩阵的长度,比如shape[0]就是读取矩阵第一维度的长度。直接用.shape可以快速
- 在windows下写bat的时候,通过pause命令,可以暂停程序运行,例如经常见的程序会在终端提示”按任意键继续……”,用户在终端回车后程
- 一、项目需求前言:BBS上每个id对应一个用户,他们注册时候会填写性别(男、女、保密三选一)。经过检查,BBS注册用户的id对应1-3000
- 本文实例讲述了python定时器(Timer)用法。分享给大家供大家参考。具体如下:# encoding: UTF-8import thre
- 一.引言先看获取到的效果拍摄时间:2021:12:18 16:22:13照片拍摄地址:('内蒙古自治区包头市昆都仑区', &
- Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。基本语法是通过 {} 和 :
- 本文介绍基于Python语言gdal模块,实现多波段HDF栅格图像文件的读取、处理与像元值可视化(直方图绘制)等操作。另外,基于gdal等模
- 因为m1芯片是arm版本的架构,以前在mac上的很多软件都是基于Intel架构的软件,apple开发了rossta2,可以在m1上运行int
- type()动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义的,而是运行时动态创建的。比方说我们要定义一个Hello的cla
- Web设计师可以使用HTML4和CSS2.1完成一些很酷的东西。我们可以在不使用陈旧的基于table布局的基础上完成文档逻辑结构并创建内容丰