![](/img/trans.png)
[英]matplotlib(mpl_connect) in for loop to create many interactive plots does not work
[英]mpl_connect inside a loop in matplotlib
它实际上不是在循环内,而是在类PPlot()
的方法内使用fig.canvas.mpl_connect
。
在主程序中,我首先首先创建绘图(使用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
只是打印__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))
...
如果我在构造函数中或在update()
之外的其他地方初始化fig.canvas.mpl_connect
,则无法使用第三个参数的列表。
我可以想象将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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.