1
2
3
4 from matplotlib import pylab as p
5 from matplotlib.text import Text
6
7
8 class DragHandler(object):
9 """ A simple class to handle Drag n Drop.
10
11 This is a simple example, which works for Text objects only.
12 """
13 def __init__(self, figure=None) :
14 """ Create a new drag handler and connect it to the figure's event system.
15 If the figure handler is not given, the current figure is used instead
16 """
17
18 if figure is None : figure = p.gcf()
19
20 self.dragged = None
21
22
23 figure.canvas.mpl_connect("pick_event", self.on_pick_event)
24 figure.canvas.mpl_connect("button_release_event", self.on_release_event)
25
26 def on_pick_event(self, event):
27 " Store which text object was picked and were the pick event occurs."
28
29 if isinstance(event.artist, Text):
30 self.dragged = event.artist
31 self.pick_pos = (event.mouseevent.xdata, event.mouseevent.ydata)
32 return True
33
34 def on_release_event(self, event):
35 " Update text position and redraw"
36
37 if self.dragged is not None :
38 old_pos = self.dragged.get_position()
39 new_pos = (old_pos[0] + event.xdata - self.pick_pos[0],
40 old_pos[1] + event.ydata - self.pick_pos[1])
41 self.dragged.set_position(new_pos)
42 self.dragged = None
43 p.draw()
44 return True
45
46
47
48 from numpy import *
49
50
51 x, y = random.normal(5, 2, size=(2, 9))
52 labels = [ "Point %d" % i for i in xrange(x.size)]
53
54
55 p.scatter(x, y)
56 p.grid()
57
58
59 for a,b,l in zip(x,y, labels):
60 p.text(a, b, l, picker=True)
61
62
63 dragh = DragHandler()
64
65 p.show()
66
67
, as shown below in the list of files. Do
link, since this is subject to change and can break easily.