我相信我没有正确使用Matplotlib的pick事件。在下面的代码中,我创建了三个指定半径和位置的不相交的橙色磁盘,这些磁盘由id号标识。
我想单击每个磁盘并向终端打印一条消息,标识磁盘、中心、半径和id。但是,每次单击磁盘时,都会触发所有磁盘的pick事件。我哪里做错了?
情节是这样的
python - 正确使用Matplotlib的pick事件-LMLPHP
这是点击磁盘1的输出
python - 正确使用Matplotlib的pick事件-LMLPHP
这是密码。

from global_config import GC
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np


class Disk:


    def __init__(self, center, radius, myid = None, figure=None, axes_object=None):
        """
        @ARGS
        CENTER : Tuple of floats
        RADIUS : Float
        """
        self.center = center
        self.radius = radius
        self.fig    = figure
        self.ax     = axes_object
        self.myid   = myid

    def onpick(self,event):
        print "You picked the disk ", self.myid, "  with Center: ", self.center, " and Radius:", self.radius


    def mpl_patch(self, diskcolor= 'orange' ):
        """ Return a Matplotlib patch of the object
        """
        mypatch =  mpl.patches.Circle( self.center, self.radius, facecolor = diskcolor, picker=1 )

        if self.fig != None:
            self.fig.canvas.mpl_connect('pick_event', self.onpick) # Activate the object's method

        return mypatch



def main():

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title('click on disks to print out a message')

    disk_list = []

    disk_list.append( Disk( (0,0), 1.0, 1, fig, ax   )   )
    ax.add_patch(disk_list[-1].mpl_patch() )

    disk_list.append( Disk( (3,3), 0.5, 2, fig, ax   )   )
    ax.add_patch(disk_list[-1].mpl_patch() )

    disk_list.append( Disk( (4,9), 2.5, 3, fig, ax   )   )
    ax.add_patch(disk_list[-1].mpl_patch() )


    ax.set_ylim(-2, 10);
    ax.set_xlim(-2, 10);

    plt.show()


if __name__ == "__main__":
    main()

最佳答案

有很多方法可以处理这个问题。我已经修改了您的代码,试图显示两种可能的方式(所以它有无关的代码,尽管您希望以何种方式处理它)。
一般来说,我认为您只需要附加一个pick_event处理程序,该处理程序将需要确定哪个对象被击中。下面的代码是这样工作的:on_pick函数捕获您的磁盘和补丁,然后返回一个函数,告诉您单击了哪个图。
如果您想坚持附加多个pick_event处理程序,可以通过调整Disk.onpick来完成,如下所示,以确定pick事件是否与此磁盘相关(每个磁盘将获得每个pick事件)。您将注意到,Disk类在self.mypatch中保存了补丁,以便工作。
如果您想这样做,请放弃我对main所做的所有更改,并取消对Disk.mpl_patch中两行的注释。

import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np


class Disk:


    def __init__(self, center, radius, myid = None, figure=None, axes_object=None):
        """
        @ARGS
        CENTER : Tuple of floats
        RADIUS : Float
        """
        self.center = center
        self.radius = radius
        self.fig    = figure
        self.ax     = axes_object
        self.myid   = myid
        self.mypatch = None


    def onpick(self,event):
        if event.artist == self.mypatch:
            print "You picked the disk ", self.myid, "  with Center: ", self.center, " and Radius:", self.radius


    def mpl_patch(self, diskcolor= 'orange' ):
        """ Return a Matplotlib patch of the object
        """
        self.mypatch = mpl.patches.Circle( self.center, self.radius, facecolor = diskcolor, picker=1 )

        #if self.fig != None:
            #self.fig.canvas.mpl_connect('pick_event', self.onpick) # Activate the object's method

        return self.mypatch

def on_pick(disks, patches):
    def pick_event(event):
        for i, artist in enumerate(patches):
            if event.artist == artist:
                disk = disks[i]
                print "You picked the disk ", disk.myid, "  with Center: ", disk.center, " and Radius:", disk.radius
    return pick_event


def main():

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title('click on disks to print out a message')

    disk_list = []
    patches = []

    disk_list.append( Disk( (0,0), 1.0, 1, fig, ax   )   )
    patches.append(disk_list[-1].mpl_patch())
    ax.add_patch(patches[-1])

    disk_list.append( Disk( (3,3), 0.5, 2, fig, ax   )   )
    patches.append(disk_list[-1].mpl_patch())
    ax.add_patch(patches[-1])

    disk_list.append( Disk( (4,9), 2.5, 3, fig, ax   )   )
    patches.append(disk_list[-1].mpl_patch())
    ax.add_patch(patches[-1])

    pick_handler = on_pick(disk_list, patches)

    fig.canvas.mpl_connect('pick_event', pick_handler) # Activate the object's method

    ax.set_ylim(-2, 10);
    ax.set_xlim(-2, 10);

    plt.show()


if __name__ == "__main__":
    main()

关于python - 正确使用Matplotlib的pick事件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37447657/

10-13 03:19