图形鼠标输入的回调-如何刷新图形,如何告诉Matplotlib我完成了



希望有人能用回调。

目标:

  • 显示包含数据的绘图
  • 允许用户在绘图上单击4次。每次,X坐标附加到已保存的列表中
  • 当鼠标移动时,其水平位置由垂直在情节中来回移动的线。(我保存2D行对象为self.currentLine)
  • 当用户通过单击选择一个点时,垂直线将在感兴趣的x坐标,并生成一个新坐标以继续跟踪鼠标位置

在用户输入结束时,应该有四条垂直线和类应该返回一个包含其x坐标的列表。

目前,我无法找到更新中的线条对象的正确方法绘图(即,这样我就可以获得我想要的鼠标跟踪效果)。我也不能完成时返回值列表的类。

我知道while循环可能不是正确的方法,但我找不出合适的方法。

import matplotlib.pyplot as plt
import pdb
class getBval:
def __init__(self):
figWH = (8,5) # in
self.fig = plt.figure(figsize=figWH)
plt.plot(range(10),range(10),'k--')
self.ax = self.fig.get_axes()[0]
self.x = [] # will contain 4 "x" values
self.lines = [] # will contain 2D line objects for each of 4 lines            
self.connect =    self.ax.figure.canvas.mpl_connect
self.disconnect = self.ax.figure.canvas.mpl_disconnect
self.mouseMoveCid = self.connect("motion_notify_event",self.updateCurrentLine)
self.clickCid     = self.connect("button_press_event",self.onClick)
def updateCurrentLine(self,event):
xx = [event.xdata]*2
self.currentLine, = self.ax.plot(xx,self.ax.get_ylim(),'k')
plt.show()
def onClick(self, event):
if event.inaxes:
self.updateCurrentLine(event)
self.x.append(event.xdata)
self.lines.append(self.currentLine)
del self.currentLine
if len(self.x)==4:
self.cleanup()
def cleanup(self):
self.disconnect(self.mouseMoveCid)
self.disconnect(self.clickCid)
return self

xvals = getBval()
print xvals.x

我建议您为垂直线使用Cursor小部件,只收集点击的x值(而不是整个Line2D),这里有一个例子:

import matplotlib.pyplot as plt
import matplotlib.widgets as mwidgets
class getBval:
def __init__(self):
figWH = (8,5) # in
self.fig = plt.figure(figsize=figWH)
plt.plot(range(10),range(10),'k--')
self.ax = self.fig.get_axes()[0]
self.x = [] # will contain 4 "x" values
self.lines = [] # will contain 2D line objects for each of 4 lines            
self.cursor = mwidgets.Cursor(self.ax, useblit=True, color='k')
self.cursor.horizOn = False
self.connect = self.ax.figure.canvas.mpl_connect
self.disconnect = self.ax.figure.canvas.mpl_disconnect
self.clickCid = self.connect("button_press_event",self.onClick)
def onClick(self, event):
if event.inaxes:
self.x.append(event.xdata)
if len(self.x)==4:
self.cleanup()
def cleanup(self):
self.disconnect(self.clickCid)
plt.close()

xvals = getBval()
plt.show()
print xvals.x

最新更新