如何区分SpanSelector中的左右按钮?

问题描述 投票:2回答:2

我想用SpanSelector在一个图中选择两个区间。为了保存间隔的不同极值,我想使用一个标志,取决于我是否使用右或左按钮选择间隔(所以我可以区分两个所需的间隔)。

以上可能吗?


编辑:

更具体一点:我希望一旦显示情节,SpanSelector绘制红色区域,如果由左按钮完成,蓝色区域由右按钮完成。


例:

下面的代码允许用户以交互方式选择间隔,然后打印这样的间隔

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.widgets as mwidgets  

fig = plt.figure() 
ax = plt.axes() 
x = np.arange(0,2*np.pi)  
y = np.sin(x) 
ax.plot(x,y) 

def onselect(vmin, vmax):
    print(vmin, vmax)

span = mwidgets.SpanSelector(ax, onselect, 'horizontal') 

plt.show()                                                               

我想修改上面的代码,如果间隔是由左按钮绘制的,那么它会打印"LEFT: vimin, vmax",如果间隔是由右按钮绘制的,那么它会打印"RIGHT: vmin, vmax"

以上可能吗?

python matplotlib widget mouse interactive
2个回答
1
投票
SpanSelector(..., button=1)

将是鼠标左键和的跨度选择器

SpanSelector(..., button=3)

将是鼠标右键的跨度选择器。


0
投票

我用mpl_connect解决了它。我没有区分左右键,但我让代码以不同的方式处理SpanSelector输入,具体取决于鼠标选择的跨度是否先前是enter击键或shift+enter击键。我留下下面的代码,以防其他人有用。

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.widgets as mwidgets  

fig = plt.figure() 
ax = plt.axes() 
x = np.arange(0,2*np.pi)  
y = np.sin(x) 
ax.plot(x,y) 
ax.set_title('[Press \'enter\' and \'shift+enter\' to select the intervals]')

def onselect(vmin, vmax):
    if plot_key_input == 'enter':
        print('Interval type 1:', vmin, vmax)
    if plot_key_input == 'enter+shift':
        print('Interval type 2:', vmin, vmax)

# The variable plot_key_input will store the key that is pressed during the plot visualization
plot_key_input = None
# Get the key pressed during the plot visualization
def onPressKey(event):
# Defined as a global variable so it will affect other programs and functions
    global plot_key_input
    plot_key_input = event.key

# Connect the keys to the function onPressKey during the plot visualization
cid = fig.canvas.mpl_connect('key_press_event', onPressKey)

span = mwidgets.SpanSelector(ax, onselect, 'horizontal') 

plt.show() 

# Disconnect the keys to the function onPressKey
fig.canvas.mpl_disconnect(cid)
© www.soinside.com 2019 - 2024. All rights reserved.