多个matplotlib连接未正确映射

时间:2013-06-12 13:52:15

标签: matplotlib pyside

我正在使用matplotlib在PySide GUI中显示数据。它绘制的每个参数都有一个轴。我想在选择轴时调用一个函数,使用'pick_event'上的mpl_connect。以下代码生成图形和轴:

class Graph(FigureCanvas):
    def __init__(self, parent):
        self.fig = Figure()
        FigureCanvas.__init__(self, self.fig)
        self.fig.set_size_inches(14, 5.6)
        self.new_axes()

    def new_axes(self):    
        self.axes = self.fig.add_subplot(111)
        self.axes.get_yaxis().set_visible(False)
        self.channel_dict = {}
        self.axes_dict = {}
        self.cursor_dict = {}

        for parameter in parameter_dict_order:
            self.axes_dict[parameter + "_l"] = self.axes.twinx()
            self.cursor_dict[parameter + "_l"] = DataCursor(self.fig.gca())
            self.fig.canvas.mpl_connect('pick_event', self.cursor_dict[parameter + "_l"])

            self.channel_dict[parameter + "_l"], = self.axes_dict[parameter + "_l"].plot(\
                [], [], \
                color = parameter_dict[parameter]['color'], \
                label = parameter)
            self.channel_dict[parameter + "_l"].set_picker(2)

            self.axes_dict[parameter + "_l"].get_yaxis().set_visible(False)
            self.axes_dict[parameter + "_l"].autoscale_view(False, True, True)

        self.fig.tight_layout()
        self.fig.canvas.draw()`

不幸的是,此实现仅对与列表中最后一项对应的轴上的拾取事件做出反应。但是,单击此轴时,将执行所有连接的函数调用。这怎么样?我如何正确使用mpl_connect?

DataCursor类:

class DataCursor(object):
    text_template = 'x: %0.2f\ny: %0.2f'
    x, y = 0.0, 0.0
    xoffset, yoffset = -20, 20
    text_template = 'x: %0.2f\ny: %0.2f'

    def __init__(self, ax):
        self.generate_annotation(ax)
        self.update = Communicate()

    def __call__(self, event):
        print 'in cursor of: ', self
        self.event = event
        self.update.foo.emit()
        self.x, self.y = event.mouseevent.xdata, event.mouseevent.ydata
        if self.x is not None:
            self.annotation.xy = self.x, self.y
            self.annotation.set_text(self.text_template % (self.x, self.y))
            self.annotation.set_visible(True)
            self.vline.set_visible(True)
            self.vline.set_xdata(self.x)
            event.canvas.draw()
        QtCore.QCoreApplication.processEvents()

    def generate_annotation(self, ax):
        self.ax = ax
        self.annotation = ax.annotate(self.text_template, 
                xy=(self.x, self.y), xytext=(self.xoffset, self.yoffset), 
                textcoords='offset points', ha='right', va='bottom',
                bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
                arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')
                )
        self.annotation.set_visible(False)
        self.vline = ax.axvline(visible = False)

0 个答案:

没有答案