mpl_connect在matplotlib中的循环内部

时间:2017-07-11 15:54:02

标签: python matplotlib

循环中不是字面,但我在我的班级fig.canvas.mpl_connect的方法中使用PPlot()

在主程序中,我首先创建绘图(使用simple_plot()),然后调用update()方法重新绘制点:

plot = PPlot()
plot.simple_plot(x_values, y_values)
...
plot.update(x_values, y_values)
...
plot.update(x_values, y_values)

这是我的代码到目前为止的样子(__onpick只打印所选点的坐标):

def update(self, x_values, y_values) -> None:
    self.sc.set_data(x_values, y_values)
    event_handler = self.fig.canvas.mpl_connect('pick_event', self.__onpick)

    self.axis.relim()
    self.axis.autoscale_view(True, True, True)

    self.fig.canvas.draw()
    plt.pause(1*10e-10)

    self.fig.canvas.mpl_disconnect(event_handler)

输出结果为:

Point = (1,2)

另一方面,如果我没有放置最后一个self.fig.canvas.mpl_disconnect(event_handler),当我多次使用update()时,输出将为:

Point = (1,2)
Point = (1,2)
Point = (1,2)
...

有更好的方法吗?难道我做错了什么?这种方法对我来说似乎不太好。

谢谢。

编辑:为了澄清,__onpick不只是打印积分,还会做其他一些事情。实际上,真正的代码是:

def update(self, x_values, y_values, biglist) -> None:
    ...
    event_handler = self.fig.canvas.mpl_connect('pick_event', 
                          lambda event: self.__onpick(event, biglist))
    ...

如果我在构造函数或fig.canvas.mpl_connect之外的其他地方初始化update(),我就无法使用第3个参数的列表。

1 个答案:

答案 0 :(得分:0)

我想让biglist成为一个类变量,只需在onpick方法中使用它,而不是将其提供给onpick方法。

import matplotlib.pyplot as plt

class PPlot():
    def __init__():
        self.biglist = None
        self.fig, self.ax = plt.subplots()
        self.cid = self.fig.canvas.mpl_connect('pick_event', self.onpick)

    def update(self, x_values, y_values, biglist):
        self.biglist = biglist
        self.sc.set_data(x_values, y_values)

        self.axis.relim()
        self.axis.autoscale_view(True, True, True)

        self.fig.canvas.draw()
        plt.pause(1*10e-10)


    def onpick(event=None):
        print (self.biglist)
        # do something with biglist



plot = PPlot()
plot.simple_plot(x_values, y_values)
#...
plot.update(x_values1, y_values1, biglist1)
#...
plot.update(x_values2, y_values2, biglist2)