Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d24de73

Browse files
committed
fixed text picking
svn path=/trunk/matplotlib/; revision=5708
1 parent b718a91 commit d24de73

2 files changed

Lines changed: 69 additions & 6 deletions

File tree

examples/api/line_with_text.py

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
"""
2+
Show how to override basic methods so an artist can contain another
3+
artist. In this case, the line contains a Text instance to label it.
4+
"""
5+
import numpy as np
6+
import matplotlib.pyplot as plt
7+
import matplotlib.lines as lines
8+
import matplotlib.transforms as mtransforms
9+
import matplotlib.text as mtext
10+
11+
12+
class MyLine(lines.Line2D):
13+
14+
def __init__(self, *args, **kwargs):
15+
# we'll update the position when the line data is set
16+
self.text = mtext.Text(0, 0, '')
17+
lines.Line2D.__init__(self, *args, **kwargs)
18+
19+
# we can't access the label attr until *after* the line is
20+
# inited
21+
self.text.set_text(self.get_label())
22+
23+
def set_figure(self, figure):
24+
self.text.set_figure(figure)
25+
lines.Line2D.set_figure(self, figure)
26+
27+
def set_axes(self, axes):
28+
self.text.set_axes(axes)
29+
lines.Line2D.set_axes(self, axes)
30+
31+
def set_transform(self, transform):
32+
# 2 pixel offset
33+
texttrans = transform + mtransforms.Affine2D().translate(2, 2)
34+
self.text.set_transform(texttrans)
35+
lines.Line2D.set_transform(self, transform)
36+
37+
38+
def set_data(self, x, y):
39+
if len(x):
40+
self.text.set_position((x[-1], y[-1]))
41+
42+
lines.Line2D.set_data(self, x, y)
43+
44+
def draw(self, renderer):
45+
# draw my label at the end of the line with 2 pixel offset
46+
lines.Line2D.draw(self, renderer)
47+
self.text.draw(renderer)
48+
49+
50+
51+
52+
53+
fig = plt.figure()
54+
ax = fig.add_subplot(111)
55+
x, y = np.random.rand(2, 20)
56+
line = MyLine(x, y, mfc='red', ms=12, label='line label')
57+
#line.text.set_text('line label')
58+
line.text.set_color('red')
59+
line.text.set_fontsize(16)
60+
61+
62+
ax.add_line(line)
63+
64+
65+
plt.show()

lib/matplotlib/text.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -135,17 +135,15 @@ def contains(self,mouseevent):
135135
"""
136136
if callable(self._contains): return self._contains(self,mouseevent)
137137

138-
try:
139-
l,b,w,h = self.get_window_extent().get_bounds()
140-
except:
141-
# TODO: why does this error occur
142-
#print str(self),"error looking at get_window_extent"
143-
return False,{}
138+
139+
l,b,w,h = self.get_window_extent().bounds
140+
144141
r = l+w
145142
t = b+h
146143
xyverts = (l,b), (l, t), (r, t), (r, b)
147144
x, y = mouseevent.x, mouseevent.y
148145
inside = nxutils.pnpoly(x, y, xyverts)
146+
149147
return inside,{}
150148

151149
def _get_xy_display(self):

0 commit comments

Comments
 (0)