正确使用Matplotlib的选择事件

时间:2016-05-25 21:08:46

标签: python matplotlib

我相信我没有正确使用Matplotlib的选择事件。在下面的代码中,我创建了三个指定半径和位置由标识号标识的不相交的橙色磁盘。

我想 - 点击每个磁盘并向终端打印一条消息,标识磁盘,中心,半径和ID。但是,每次单击磁盘时,都会触发 所有 磁盘的选择事件。我哪里错了?

这是情节

enter image description here

以下是点击磁盘1的输出

enter image description here

这是代码。

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()

1 个答案:

答案 0 :(得分:5)

有很多方法可以解决这个问题。我修改了你的代码,试图展示两种可能的方式(所以它有无关的代码,尽管你想要处理它的方式)。

通常,我认为您只附加了一个pick_event处理程序,并且该处理程序需要确定哪个对象被命中。下面的代码以这种方式运行on_pick函数捕获磁盘和补丁,然后返回一个函数来判断单击了哪个数字。

如果您想坚持使用多个pick_event处理程序,可以通过调整Disk.onpick来完成此操作,如下所示,以确定pick事件是否与此磁盘相关(每个磁盘都将获得每个选秀活动)。您将注意到磁盘类在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()
相关问题