【问题标题】:Using Matplotlib's pick event properly正确使用 Matplotlib 的 pick 事件
【发布时间】:2016-05-26 21:49:31
【问题描述】:

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

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

这是剧情

这是单击磁盘 1 时的输出

这里是代码。

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

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    有很多方法可以处理这个问题。我已经修改了您的代码以尝试显示两种可能的方式(因此它具有无关的代码,尽管您希望以哪种方式处理它)。

    一般来说,我认为您只需附加一个 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 的信息。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    相关资源
    最近更新 更多