Hoping someone can tell me what I'm doing wrong in my first program using callbacks.
The goal:
- Show a plot containing data
- Allow the user to click on the plot 4 times. Each time, the X-coordinate is appended to a saved list.
- While the mouse is moving, its horizontal location is tracked by a vertical
line that moves back and forth within the plot. (I save the 2D line
object as
self.currentLine
) - When user selects a point by clicking, the vertical line is dropped at the x-coordinate of interest, and a new one is generated to continue tracking mouse position.
At the end of user input, there should be four vertical lines and the class should return a list containing their x-coordinates.
At present, I can't figure out the proper way to update the line objects in the plot (i.e. so I can get the mouse tracking effect I want). I also can't get the class to return the list of values when finished.
I know the while
loop probably isn't the right approach, but I can't figure out the proper one.
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