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 the final x, y coordinates(x1, y1)
. But completely clueless why the selection area is not showing up.
from Tkinter import *
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = Tk()
graph = Figure(figsize=(5,4), dpi=100)
ax = graph.add_subplot(111)
plot = ax.plot([1,2,3,4],[5,6,2,8])
canvas = FigureCanvasTkAgg(graph, master=root)
canvas.show()
canvas.get_tk_widget().grid(column=2, row=1, rowspan=2, sticky=(N, S, E, W))
class Zoom(object):
def __init__(self):
self.graph = Figure(figsize=(5,4), dpi=100)
self.ax = graph.add_subplot(111)
self.rect = ax.patch
self.rect.set_facecolor('green')
self.ax.plot([1,2,3,4],[5,6,2,8])
self.is_pressed = False
self.x0 = None
self.y0 = None
self.x1 = None
self.y1 = None
self.aid = graph.canvas.mpl_connect('button_press_event', self.on_press)
self.bid = graph.canvas.mpl_connect('button_release_event', self.on_release)
self.cid = graph.canvas.mpl_connect('motion_notify_event', self.on_motion)
def on_press(self, event):
print 'press'
self.is_pressed = True
self.x0 = event.xdata
self.y0 = event.ydata
print(self.x1, self.x0)
print(self.y1, self.y0)
def on_motion(self, event):
if self.is_pressed is True:
print 'panning'
self.x1 = event.xdata
self.y1 = event.ydata
print(self.x1, self.x0)
print(self.y1, self.y0)
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 = event.xdata
self.y1 = event.ydata
print(self.x1, self.x0)
print(self.y1, self.y0)
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('solid')
self.ax.figure.canvas.draw()
my_object = Zoom()
root.mainloop()
I have taken help from this question Matplotlib: draw a selection area in the shape of a rectangle with the mouse The output I am getting is
press
(0.0, 1.4007056451612905)
(0.0, 6.9296116504854366)
panning
(1.4007056451612905, 1.4007056451612905)
(6.8932038834951452, 6.9296116504854366)
panning
(None, 1.4007056451612905)
(None, 6.9296116504854366)
panning
(None, 1.4007056451612905)
(None, 6.9296116504854366)
release
(None, 1.4007056451612905)
(None, 6.9296116504854366)