【问题标题】:How to distinguishing right and left button in SpanSelector?如何区分 SpanSelector 中的左右按钮?
【发布时间】:2023-12-22 15:03:01
【问题描述】:

我想使用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


    【解决方案1】:
    SpanSelector(..., button=1)
    

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

    SpanSelector(..., button=3)
    

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

    【讨论】:

    • 感谢您的提示。这有帮助,但我仍然没有得到我想要的。为了更准确,我在上面编辑了我的问题。
    • 这个答案建议使用 两个 SpanSelectors。
    【解决方案2】:

    我使用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)
    

    【讨论】:

      最近更新 更多