Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Matplotlib event handling: interaction with pan/zoom

I am using matplotlib's event handling on a 2d array. I have a class which basically sets to 0 the elements of the array selected by drawing a rectangle by hand on the canvas.

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)

The problem is that, if I want to zoom some detail and, after to drag/pan on the axis, event handling occurs and sets to 0 the rectangle I am trying to zoom. How do I modify my function in such a way that rectangles are set to 0 only if I am not in zoom or pan mode?

like image 401
fmonegaglia Avatar asked Jul 21 '26 02:07

fmonegaglia


1 Answers

Try adding this as the first line of your onpress function:

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

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

like image 178
Chuan Li Avatar answered Jul 22 '26 23:07

Chuan Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!