I am developing an application which lets user Zoom a part of the graph based on their selection. I am able to get the initial x, y coordinates(x0, y0)
and also
You need to update these as the event changes:
def on_motion(self, event):
if self.is_pressed is True:
self.x1 = event.xdata
self.y1 = event.ydata
self.rect.set_width(1)
self.rect.set_height(1)
self.rect.set_xy((2.5, 5))
self.rect.set_linestyle('dashed')
self.ax.figure.canvas.draw()
def on_release(self, event):
print 'release'
self.is_pressed = False
self.x1 = event.xdata
self.y1 = event.ydata
self.rect.set_width(1)
self.rect.set_height(1)
self.rect.set_xy((2.5, 5))
self.rect.set_linestyle('solid')
self.ax.figure.canvas.draw()
As is they will continually draw a fixed size rectangle at the coordinates (2.5, 5) with a width and height of 1.
Similar to the question you were looking at something like this works.
def on_press(self, event):
print('press')
self.is_pressed = True
self.x0 = event.xdata
self.y0 = event.ydata
def on_motion(self, event):
self.x1, self.y1 = event.xdata, event.ydata
if (self.is_pressed is True and
self.x1 is not None and
self.y1 is not None):
self.rect.set_width(self.x1 - self.x0)
self.rect.set_height(self.y1 - self.y0)
self.rect.set_xy((self.x0, self.y0))
self.rect.set_linestyle('dashed')
self.ax.figure.canvas.draw()
def on_release(self, event):
print('release')
self.is_pressed = False
self.x1, self.y1 = event.xdata, event.ydata
try:
self.rect.set_width(self.x1 - self.x0)
self.rect.set_height(self.y1 - self.y0)
self.rect.set_xy((self.x0, self.y0))
except TypeError:
if (self.x1 is None or self.y1 is None):
return
else:
raise
self.rect.set_linestyle('solid')
self.ax.figure.canvas.draw()
Notice that the rectangle dimensions are taken from the event. I added the guard to prevent mishaps where the event does not properly interpret the coordinate.
@furas makes a good points in the comments, it is a good idea to initialize your coordinates to floats.
self.x0 = 0.0
self.y0 = 0.0
self.x1 = 0.0
self.y1 = 0.0