matplotlib之多邊形選區(qū)(PolygonSelector)的使用
多邊形選區(qū)概述
多邊形選區(qū)是一種常見(jiàn)的對(duì)象選擇方式,在一個(gè)子圖中,單擊鼠標(biāo)左鍵即構(gòu)建一個(gè)多邊形的端點(diǎn),最后一個(gè)端點(diǎn)與第一個(gè)端點(diǎn)重合即完成多邊形選區(qū),選區(qū)即為多個(gè)端點(diǎn)構(gòu)成的多邊形。在matplotlib中的多邊形選區(qū)屬于部件(widgets),matplotlib中的部件都是中性(neutral )的,即與具體后端實(shí)現(xiàn)無(wú)關(guān)。
多邊形選區(qū)具體實(shí)現(xiàn)定義為matplotlib.widgets.PolygonSelector類(lèi),繼承關(guān)系為:Widget->AxesWidget->_SelectorWidget->PolygonSelector。
PolygonSelector類(lèi)的簽名為class matplotlib.widgets.PolygonSelector(ax, onselect, useblit=False, lineprops=None, markerprops=None, vertex_select_radius=15)
PolygonSelector類(lèi)構(gòu)造函數(shù)的參數(shù)為:
- ax:多邊形選區(qū)生效的子圖,類(lèi)型為matplotlib.axes.Axes的實(shí)例。
- onselect:多邊形選區(qū)完成后執(zhí)行的回調(diào)函數(shù),函數(shù)簽名為def onselect( vertices),vertices數(shù)據(jù)類(lèi)型為列表,列表元素格式為(xdata,ydata)元組。
- drawtype:多邊形選區(qū)的外觀,取值范圍為{"box", "line", "none"},"box"為多邊形框,"line"為多邊形選區(qū)對(duì)角線,"none"無(wú)外觀,類(lèi)型為字符串,默認(rèn)值為"box"。
- lineprops:多邊形選區(qū)線條的屬性,默認(rèn)值為dict(color='k', linestyle='-', linewidth=2, alpha=0.5)。
- markerprops:多邊形選區(qū)端點(diǎn)的屬性,默認(rèn)值為dict(marker='o', markersize=7, mec='k', mfc='k', alpha=0.5)。
- vertex_select_radius:多邊形端點(diǎn)的選擇半徑,浮點(diǎn)數(shù),默認(rèn)值為15,用于端點(diǎn)選擇或者多邊形閉合。
PolygonSelector類(lèi)中的state_modifier_keys公有變量 state_modifier_keys定義了操作快捷鍵,類(lèi)型為字典。
- “move_all”: 移動(dòng)已存在的選區(qū),默認(rèn)為"shift"。
- “clear”:清除現(xiàn)有選區(qū),默認(rèn)為 "escape",即esc鍵。
- “move_vertex”:正方形選區(qū),默認(rèn)為"control"。
PolygonSelector類(lèi)中的verts特性返回多邊形選區(qū)中的多有端點(diǎn),類(lèi)型為列表,元素為(x,y)元組,即端點(diǎn)的坐標(biāo)元組。
案例
官方案例,https://matplotlib.org/gallery/widgets/polygon_selector_demo.html
案例說(shuō)明

單擊鼠標(biāo)左鍵創(chuàng)建端點(diǎn),最終點(diǎn)擊初始端點(diǎn)閉合多邊形,形成多邊形選區(qū)。選區(qū)外的數(shù)據(jù)元素顏色變淡,選區(qū)內(nèi)數(shù)據(jù)顏色保持不變。
按esc鍵取消選區(qū)。按shift鍵鼠標(biāo)可以移動(dòng)多邊形選區(qū)位置,按ctrl鍵鼠標(biāo)可以移動(dòng)多邊形選區(qū)某個(gè)端點(diǎn)的位置。退出程序時(shí),控制臺(tái)輸出選區(qū)內(nèi)數(shù)據(jù)元素的坐標(biāo)。
控制臺(tái)輸出:
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])
到此這篇關(guān)于matplotlib之多邊形選區(qū)(PolygonSelector)的使用的文章就介紹到這了,更多相關(guān)matplotlib 多邊形選區(qū)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)list元素按關(guān)鍵字相加減的方法示例
這篇文章主要介紹了python實(shí)現(xiàn)list元素按關(guān)鍵字相加減的方法,結(jié)合具體實(shí)例形式分析了Python針對(duì)list元素遍歷與運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2017-06-06
python刪除指定類(lèi)型(或非指定)的文件實(shí)例詳解
這篇文章主要介紹了python刪除指定類(lèi)型(或非指定)的文件,以實(shí)例形式較為詳細(xì)的分析了Python刪除文件的相關(guān)技巧,需要的朋友可以參考下2015-07-07
Python的pytest測(cè)試框架中fixture的使用詳解
這篇文章主要介紹了pytest中fixture的使用詳解,pytest是一個(gè)非常成熟的全功能的Python測(cè)試框架,能夠支持簡(jiǎn)單的單元測(cè)試和復(fù)雜的功能測(cè)試,還可以用來(lái)做selenium/appnium等自動(dòng)化測(cè)試、接口自動(dòng)化測(cè)試,需要的朋友可以參考下2023-07-07
tensorflow 分類(lèi)損失函數(shù)使用小記
這篇文章主要介紹了tensorflow 分類(lèi)損失函數(shù)使用小記,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
python計(jì)算機(jī)視覺(jué)opencv卡號(hào)識(shí)別示例詳解
這篇文章主要為大家介紹了python計(jì)算機(jī)視覺(jué)opencv卡號(hào)識(shí)別的實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下 希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
python自動(dòng)化測(cè)試之setUp與tearDown實(shí)例
這篇文章主要介紹了python自動(dòng)化測(cè)試之setUp與tearDown實(shí)例,其中setUp()方法中進(jìn)行測(cè)試前的初始化工作,并在tearDown()方法中執(zhí)行測(cè)試后的清除工作,setUp()和tearDown()都是TestCase類(lèi)中定義的方法,需要的朋友可以參考下2014-09-09
基于Flask實(shí)現(xiàn)的Windows事件ID查詢系統(tǒng)
Windows操作系統(tǒng)的事件日志系統(tǒng)記錄了數(shù)百種不同的事件ID,每個(gè)ID對(duì)應(yīng)特定的系統(tǒng)事件,本文介紹如何構(gòu)建一個(gè)基于Web的事件ID查詢系統(tǒng),文章通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2025-04-04
一篇文章帶你了解python標(biāo)準(zhǔn)庫(kù)--os模塊
在本篇內(nèi)容里小編給大家整理的是關(guān)于Python中os模塊及用法相關(guān)知識(shí)點(diǎn),有興趣的朋友們可以學(xué)習(xí)下,希望能給你帶來(lái)幫助2021-08-08
解決python 自動(dòng)安裝缺少模塊的問(wèn)題
今天小編就為大家分享一篇解決python 自動(dòng)安裝缺少模塊的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10
Python爬蟲(chóng)實(shí)戰(zhàn)演練之采集糗事百科段子數(shù)據(jù)
讀萬(wàn)卷書(shū)不如行萬(wàn)里路,只學(xué)書(shū)上的理論是遠(yuǎn)遠(yuǎn)不夠的,只有在實(shí)戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用Python采集糗事百科段子的數(shù)據(jù),大家可以在過(guò)程中查缺補(bǔ)漏,提升水平2021-10-10

