同一图中的多个画布连接

时间:2014-01-03 14:15:27

标签: canvas matplotlib event-handling

我有一个有3个轴的图。我通过mpl_connect'pick_event'连接到其中的2个,它在第3轴上绘制了一些内容。示例(我省略了无关的变量和代码的某些部分,使其更加清晰和简单):

class ManualElimination:
    def __init__(self):
        self.fig=figure()
        self.cid2=None
        self.cid1=None
        self.data1=None
        self.data2=None
        nrows=2
        ncols=4
        self.ax1=plt.subplot2grid((nrows, ncols), (0, 0), colspan=1, rowspan=1)
        self.ax2=plt.subplot2grid((nrows, ncols), (0, 1), colspan=1, rowspan=1)
        self.ax4=plt.subplot2grid((nrows, ncols), (1, 0), colspan=ncols-1, rowspan=1)
        self._replot()
    def _onpick_plot_2(self, event):
        try:
            self.x=self.cat[self.keys[self.ind]].members[int(self.data2[event.ind[0],-1])]
            self.pickedid=self.x.id
            self._replot()
            self._onpick_plot_flux()
        except:
            self.x=None
            self.pickedid=None
            self._replot()
            pass
    def _onpick_plot_1(self, event):
        try:
            self.x=self.cat[self.keys[self.ind]].members[int(self.data1[event.ind[0],-1])]
            self.pickedid=self.x.id
            self._replot() # I need this to plot the selected point in different color; this is not included in this code example to make it more simple
            self._onpick_plot_flux()
        except:
            self.x=None
            self.pickedid=None
            self._replot()
            pass
    def _onpick_plot_flux(self):
        x=self.x
        self.ax4.cla()
        sp = np.loadtxt(filename)
        self.ax4.plot(sp[:,0], sp[:,1])
        show()

    def _replot(self):
        self._clear_axes() # not defined in this example; clears all 4 axes
        self._get_data_all() # not defined here, affects self.data1 and self.data2

        if self.data1 is not None:
            self.line=self.ax1.scatter(self.data1[:,2], self.data1[:,0], picker=5)
            self.cid1=self.fig.canvas.mpl_connect('pick_event', self._onpick_plot_1)

        if self.data2 is not None:
            self.line=self.ax2.scatter(self.data2[:,2], self.data2[:,0], picker=5)
            self.cid2=self.fig.canvas.mpl_connect('pick_event', self._onpick_plot_2)

        self.fig.canvas.show()

当我在其中一个轴上选择一个点(ax1ax2)时,似乎会调用一个随机函数(self._onpick_plot_1self._onpick_plot_2)。连接具有不同的ID(self.cid1!=self.cid2)。如何调用与拾取点的轴对应的正确函数?

1 个答案:

答案 0 :(得分:0)

我首先使用axes_enter_event来检测每个轴,然后连接pick_event,然后将相应的函数作为参数传递。示例:if event.inaxes==self.ax1: self.fig.mpl_connect('pick_event', self._onpick_plot_1)