Python Matplotlib事件处理:与pan / zoom交互

时间:2016-05-11 12:45:51

标签: python matplotlib event-handling

我在二维数组上使用matplotlib的事件处理。 我有一个类,它基本上设置为0,通过在画布上手工绘制矩形来选择数组的元素。

MWE:

import numpy as np
import matplotlib.pyplot as plt

def clean( bw ):
    plt.ioff()
    fig = plt.figure()
    plt.title( 'Press-drag a rectangle for your mask. Close when you are finish.' )
    plt.imshow( bw, cmap='binary_r' )
    plt.axis('equal')
    x_press = None
    y_press = None
    def onpress(event):
        global x_press, y_press
        x_press = int(event.xdata) if (event.xdata != None) else None
        y_press = int(event.ydata) if (event.ydata != None) else None
    def onrelease(event):
        global x_press, y_press
        x_release = int(event.xdata) if (event.xdata != None) else None
        y_release = int(event.ydata) if (event.ydata != None) else None
        if (x_press != None and y_press != None
            and x_release != None and y_release != None):
            (xs, xe) = (x_press, x_release+1) if (x_press <= x_release) \
              else (x_release, x_press+1)
            (ys, ye) = (y_press, y_release+1) if (y_press <= y_release) \
              else (y_release, y_press+1)
            print( "Slice [{0}:{1},{2}:{3}] will be set to {4}".format(
                xs, xe, ys, ye, 0) )
            self.bw[ ys:ye,xs:xe ] = 0
            plt.fill( [xs,xe,xe,xs,xs], [ys,ys,ye,ye,ys], 'r', alpha=0.25 )
            event.canvas.draw()
        x_press = None
        y_press = None
    cid_press   = fig.canvas.mpl_connect('button_press_event'  , onpress  )
    cid_release = fig.canvas.mpl_connect('button_release_event', onrelease)
    plt.show()
    return bw


A = np.eye((10,10))
new_A = clean(A)

问题在于,如果我想缩放一些细节,在轴上拖动/平移后,会发生事件处理并将我想要缩放的矩形设置为0。 如果我不处于缩放或平移模式,如何修改我的功能,使矩形设置为0?

1 个答案:

答案 0 :(得分:1)

尝试将此添加为onpress功能的第一行:

if plt.get_current_fig_manager().toolbar.mode != '': return

来源: http://www.ster.kuleuven.be/~pieterd/python/html/plotting/interactive.html