【问题标题】:Python Matplotlib event handling: interaction with pan/zoomPython Matplotlib 事件处理:与平移/缩放交互
【发布时间】:2016-05-11 12:45:50
【问题描述】:

我在二维数组上使用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?

【问题讨论】:

    标签: python matplotlib event-handling


    【解决方案1】:

    尝试将其添加为 onpress 函数的第一行:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-26
      • 2020-04-12
      • 1970-01-01
      • 2017-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-01-21
      相关资源
      最近更新 更多