Attachment 'Text_DragnDrop.py'
Download
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
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 # simple attibute to store the dragged text object
20 self.dragged = None
21
22 # Connect events and callbacks
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.is_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.is_dragged is not None :
38 old_pos = self.is_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.is_dragged.set_position(new_pos)
42 self.is_dragged = None
43 p.draw()
44 return True
45
46
47 # Usage example
48 from numpy import *
49
50 # Create arbitrary points and labels
51 x, y = random.normal(5, 2, size=(2, 9))
52 labels = [ "Point %d" % i for i in xrange(x.size)]
53
54 # trace a scatter plot
55 p.scatter(x, y)
56 p.grid()
57
58 # add labels and set their picker attribute to True
59 for a,b,l in zip(x,y, labels):
60 p.text(a, b, l, picker=True)
61
62 # Create the event hendler
63 dragh = DragHandler()
64
65 p.show()
66
67 # vim: set et:
New Attachment
Attached Files
To refer to attachments on a page, use
attachment:filename, as shown below in the list of files. Do
NOT use the URL of the
[get] link, since this is subject to change and can break easily.
- [get | view] (2008年02月03日 18:20:08, 1.9 KB) [[attachment:Text_DragnDrop.py]]
- [get | view] (2008年02月03日 18:31:39, 1.9 KB) [[attachment:Text_DragnDrop_v0.1.py]]
- [get | view] (2008年02月03日 18:29:47, 1.9 KB) [[attachment:Text_DragnDrop_v2.py]]