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

Skip to content

Commit 56b4892

Browse files
committed
ported unit support to bar, errorbar, vlines and hlines
svn path=/trunk/matplotlib/; revision=3257
1 parent 235656a commit 56b4892

13 files changed

Lines changed: 190 additions & 65 deletions

File tree

examples/clippath_test.py

Lines changed: 57 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,66 @@
11
from pylab import figure, show, nx
2+
import matplotlib.transforms as transforms
23
from matplotlib.patches import RegularPolygon
34
import matplotlib.agg as agg
45

5-
fig = figure(figsize=(8,8))
6-
ax = fig.add_subplot(111, aspect='equal')
7-
t = nx.arange(0.0, 4.0, 0.01)
8-
s = 2*nx.sin(2*nx.pi*8*t)
9-
line, = ax.plot(t, s)
10-
line2, = ax.plot(t, 0.5*s, '--')
116

7+
class ClipWindow:
8+
def __init__(self, ax, line):
9+
self.ax = ax
10+
ax.set_title('drag polygon around to test clipping')
11+
self.canvas = ax.figure.canvas
12+
self.line = line
13+
self.poly = RegularPolygon(
14+
(200, 200), numVertices=10, radius=100,
15+
facecolor='yellow', alpha=0.25,
16+
transform=transforms.identity_transform())
17+
18+
ax.add_patch(self.poly)
19+
self.canvas.mpl_connect('button_press_event', self.onpress)
20+
self.canvas.mpl_connect('button_release_event', self.onrelease)
21+
self.canvas.mpl_connect('motion_notify_event', self.onmove)
22+
self.x, self.y = None, None
23+
24+
25+
def onpress(self, event):
26+
self.x, self.y = event.x, event.y
27+
28+
def onrelease(self, event):
29+
self.x, self.y = None, None
1230

31+
def onmove(self, event):
1332

14-
markers, = ax.plot(t, 2*(nx.mlab.rand(len(t))-0.5), 'bo')
15-
path = agg.path_storage()
16-
poly = RegularPolygon( (2, 0.), numVertices=100, radius=1.5,
17-
facecolor='yellow', alpha=0.25)
33+
if self.x is None: return
34+
dx = event.x - self.x
35+
dy = event.y - self.y
36+
self.x, self.y = event.x, event.y
37+
x, y = self.poly.xy
38+
x += dx
39+
y += dy
40+
#print self.y, event.y, dy, y
41+
self.poly.xy = x,y
42+
self._clip()
43+
44+
def _clip(self):
45+
fig = self.ax.figure
46+
l,b,w,h = fig.bbox.get_bounds()
47+
path = agg.path_storage()
48+
49+
for i, xy in enumerate(self.poly.get_verts()):
50+
x,y = xy
51+
y = h-y
52+
if i==0: path.move_to(x,y)
53+
else: path.line_to(x,y)
54+
path.close_polygon()
55+
self.line.set_clip_path(path)
56+
self.canvas.draw_idle()
57+
58+
59+
fig = figure(figsize=(8,8))
60+
ax = fig.add_subplot(111)
61+
t = nx.arange(0.0, 4.0, 0.01)
62+
s = 2*nx.sin(2*nx.pi*8*t)
1863

19-
ax.add_patch(poly)
20-
for i, xy in enumerate(ax.transData.seq_xy_tups(poly.get_verts())):
21-
if i==0: path.move_to(*xy)
22-
else: path.line_to(*xy)
23-
path.close_polygon()
24-
line.set_clip_path(path)
25-
line2.set_clip_path(path)
64+
line, = ax.plot(t, 2*(nx.mlab.rand(len(t))-0.5), 'b-')
65+
clipwin = ClipWindow(ax, line)
2666
show()

examples/units/artist_tests.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
if you want to initialize them with unit data, or else they will not
77
know how to convert the units to scalars
88
"""
9+
import random
910
import matplotlib.lines as lines
1011
import matplotlib.patches as patches
1112
import matplotlib.text as text
@@ -21,9 +22,19 @@
2122
ax.xaxis.set_units(cm)
2223
ax.yaxis.set_units(cm)
2324

25+
# test a line collection
26+
verts = []
27+
for i in range(10):
28+
# a random line segment in inches
29+
verts.append(zip(*inch*10*nx.mlab.rand(2, random.randint(2,15))))
30+
lc = collections.LineCollection(verts, axes=ax)
31+
ax.add_collection(lc)
32+
33+
# test a plain-ol-line
2434
line = lines.Line2D([0*cm, 1.5*cm], [0*cm, 2.5*cm], lw=2, color='black', axes=ax)
2535
ax.add_line(line)
2636

37+
# test a patch
2738
rect = patches.Rectangle( (1*cm, 1*cm), width=5*cm, height=2*cm, alpha=0.2, axes=ax)
2839
ax.add_patch(rect)
2940

examples/units/bar_unit_demo.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#!/usr/bin/env python
2+
from basic_units import cm, inch
3+
from pylab import figure, show,nx
4+
5+
N = 5
6+
menMeans = (150*cm, 160*cm, 146*cm, 172*cm, 155*cm)
7+
menStd = (20*cm, 30*cm, 32*cm, 10*cm, 20*cm)
8+
9+
fig = figure()
10+
ax = fig.add_subplot(111)
11+
12+
ind = nx.arange(N) # the x locations for the groups
13+
width = 0.35 # the width of the bars
14+
p1 = ax.bar(ind, menMeans, width, color='r', bottom=0*cm, yerr=menStd)
15+
16+
womenMeans = (145*cm, 149*cm, 172*cm, 165*cm, 200*cm)
17+
womenStd = (30*cm, 25*cm, 20*cm, 31*cm, 22*cm)
18+
p2 = ax.bar(ind+width, womenMeans, width, color='y', bottom=0*cm, yerr=womenStd)
19+
20+
ax.set_title('Scores by group and gender')
21+
ax.set_xticks(ind+width)
22+
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )
23+
24+
ax.legend( (p1[0], p2[0]), ('Men', 'Women') )
25+
ax.yaxis.set_units(inch)
26+
ax.autoscale_view()
27+
28+
#savefig('barchart_demo')
29+
show()

examples/units/basic_units.py

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import matplotlib
2-
matplotlib.rcParams['units'] = True
1+
import math
2+
33

44
import matplotlib.units as units
55
import matplotlib.ticker as ticker
@@ -95,7 +95,8 @@ def __call__(self, *args):
9595
class TaggedValue (object):
9696

9797
__metaclass__ = TaggedValueMeta
98-
_proxies = {'__add__':ConvertAllProxy,
98+
_proxies = {'__add__':ConvertAllProxy,
99+
'__sub__':ConvertAllProxy,
99100
'__mul__':ConvertAllProxy,
100101
'__rmul__':ConvertAllProxy,
101102
'__len__':PassThroughProxy}
@@ -124,7 +125,7 @@ def get_compressed_copy(self, mask):
124125
compressed_value = nx.ma.masked_array(self.value, mask=mask).compressed()
125126
return TaggedValue(compressed_value, self.unit)
126127

127-
def __getattribute__(self, name):
128+
def __getattribute__(self, name):
128129
if (name.startswith('__')):
129130
return object.__getattribute__(self, name)
130131
variable = object.__getattribute__(self, 'value')
@@ -133,10 +134,10 @@ def __getattribute__(self, name):
133134
return object.__getattribute__(self, name)
134135

135136
def __array__(self, t = None, context = None):
136-
if t:
137+
if t is not None:
137138
return nx.asarray(self.value).astype(t)
138139
else:
139-
return nx.asarray(self.value)
140+
return nx.asarray(self.value, 'O')
140141

141142
def __array_wrap__(self, array, context):
142143
return TaggedValue(array, self.unit)
@@ -211,7 +212,7 @@ def __array_wrap__(self, array, context):
211212

212213
def __array__(self, t=None, context=None):
213214
ret = nx.array([1])
214-
if (t):
215+
if t is not None:
215216
return ret.astype(t)
216217
else:
217218
return ret
@@ -344,6 +345,16 @@ def default_units(x):
344345
default_units = staticmethod(default_units)
345346

346347

348+
349+
def cos( x ):
350+
if ( iterable(x) ):
351+
result = []
352+
for val in x:
353+
result.append( math.cos( val.convert_to( radians ).get_value() ) )
354+
return result
355+
else:
356+
return math.cos( x.convert_to( radians ).get_value() )
357+
347358
basicConverter = BasicUnitConverter()
348359
units.registry[BasicUnit] = basicConverter
349360
units.registry[TaggedValue] = basicConverter

examples/units/evans_test2.py

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,20 +3,11 @@
33
This example shows how the unit class can determine the tick locating,
44
formatting and axis labeling.
55
"""
6-
from basic_units import radians, degrees
6+
from basic_units import radians, degrees, cos
77
from pylab import figure, show, nx
88
from matplotlib.cbook import iterable
99
import math
1010

11-
def cos( x ):
12-
if ( iterable(x) ):
13-
result = []
14-
for val in x:
15-
result.append( math.cos( val.convert_to( radians ).get_value() ) )
16-
return result
17-
else:
18-
return math.cos( x.convert_to( radians ).get_value() )
19-
2011

2112
x = nx.arange(0, 15, 0.01) * radians
2213

examples/units/radian_demo.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
from basic_units import radians, degrees
1+
from basic_units import radians, degrees, cos
22
from pylab import figure, show, nx
33

44
x = nx.arange(0, 15, 0.01) * radians
55

66
fig = figure()
77

88
ax = fig.add_subplot(211)
9-
ax.plot(x, nx.cos(x), xunits=radians)
9+
ax.plot(x, cos(x), xunits=radians)
1010

1111
ax = fig.add_subplot(212)
12-
ax.plot(x, nx.cos(x), xunits=degrees)
12+
ax.plot(x, cos(x), xunits=degrees)
1313

1414
show()
1515

lib/matplotlib/artist.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,13 @@ def __init__(self):
4848
self._propobservers = {} # a dict from oids to funcs
4949
self.axes = None
5050

51+
def have_units(self):
52+
'return True if units are set on the x or y axes'
53+
ax = self.axes
54+
if ax is None or ax.xaxis is None:
55+
return False
56+
return ax.xaxis.have_units() or ax.yaxis.have_units()
57+
5158
def convert_xunits(self, x):
5259
"""for artists in an axes, if the xaxis as units support,
5360
convert x using xaxis unit type

0 commit comments

Comments
 (0)