矩形選區概述
矩形選區是一種常見的對象選擇方式,這個名詞最常見于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” 可以組合使用。
案例
官方案例,https://matplotlib.org/gallery/widgets/rectangle_selector.html
案例說明
拖動鼠標畫出矩形選區,默認為交互模式,顯示選區框,按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 矩形選區內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!