Skip to content

Commit 8c7fab7

Browse files
committed
Use np.stack / np.column_stack where possible.
1 parent d7162a5 commit 8c7fab7

19 files changed

+83
-133
lines changed

examples/api/custom_projection_example.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -395,18 +395,17 @@ def __init__(self, resolution):
395395
self._resolution = resolution
396396

397397
def transform_non_affine(self, ll):
398-
longitude = ll[:, 0:1]
399-
latitude = ll[:, 1:2]
398+
longitude, latitude = ll.T
400399

401400
# Pre-compute some values
402-
half_long = longitude / 2.0
401+
half_long = longitude / 2
403402
cos_latitude = np.cos(latitude)
404-
sqrt2 = np.sqrt(2.0)
403+
sqrt2 = np.sqrt(2)
405404

406-
alpha = np.sqrt(1.0 + cos_latitude * np.cos(half_long))
407-
x = (2.0 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
405+
alpha = np.sqrt(1 + cos_latitude * np.cos(half_long))
406+
x = (2 * sqrt2) * (cos_latitude * np.sin(half_long)) / alpha
408407
y = (sqrt2 * np.sin(latitude)) / alpha
409-
return np.concatenate((x, y), 1)
408+
return np.column_stack([x, y])
410409
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
411410

412411
def transform_path_non_affine(self, path):

examples/misc/demo_ribbon_box.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def __init__(self, color):
3030
self.original_image.dtype)
3131

3232
im[:, :, :3] = self.b_and_h[:, :, np.newaxis]
33-
im[:, :, :3] -= self.color[:, :, np.newaxis]*(1. - np.array(rgb))
33+
im[:, :, :3] -= self.color[:, :, np.newaxis] * (1 - np.array(rgb))
3434
im[:, :, 3] = self.alpha
3535

3636
self.im = im

examples/mplot3d/trisurf3d.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,7 @@
1616

1717
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
1818
radii = np.linspace(0.125, 1.0, n_radii)
19-
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
20-
21-
# Repeat all angles for each radius.
22-
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
19+
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)[..., np.newaxis]
2320

2421
# Convert polar (radii, angles) coords to cartesian (x, y) coords.
2522
# (0, 0) is manually added at this stage, so there will be no duplicate

examples/pyplots/boxplot_demo_pyplot.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
center = np.ones(25) * 50
1818
flier_high = np.random.rand(10) * 100 + 100
1919
flier_low = np.random.rand(10) * -100
20-
data = np.concatenate((spread, center, flier_high, flier_low), 0)
20+
data = np.concatenate((spread, center, flier_high, flier_low))
2121

2222
###############################################################################
2323

@@ -64,7 +64,7 @@
6464
center = np.ones(25) * 40
6565
flier_high = np.random.rand(10) * 100 + 100
6666
flier_low = np.random.rand(10) * -100
67-
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)
67+
d2 = np.concatenate((spread, center, flier_high, flier_low))
6868
data.shape = (-1, 1)
6969
d2.shape = (-1, 1)
7070

examples/shapes_and_collections/ellipse_collection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
y = np.arange(15)
1313
X, Y = np.meshgrid(x, y)
1414

15-
XY = np.hstack((X.ravel()[:, np.newaxis], Y.ravel()[:, np.newaxis]))
15+
XY = np.column_stack((X.ravel(), Y.ravel()))
1616

1717
ww = X / 10.0
1818
hh = Y / 15.0

examples/shapes_and_collections/line_collection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
# Here are many sets of y to plot vs x
2323
ys = x[:50, np.newaxis] + x[np.newaxis, :]
2424

25-
segs = np.zeros((50, 100, 2), float)
25+
segs = np.zeros((50, 100, 2))
2626
segs[:, :, 1] = ys
2727
segs[:, :, 0] = x
2828

examples/specialty_plots/mri_with_eeg.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,11 +40,10 @@
4040
ax1.set_ylabel('MRI density')
4141

4242
# Load the EEG data
43-
numSamples, numRows = 800, 4
43+
n_samples, n_rows = 800, 4
4444
with cbook.get_sample_data('eeg.dat') as eegfile:
45-
data = np.fromfile(eegfile, dtype=float)
46-
data.shape = (numSamples, numRows)
47-
t = 10.0 * np.arange(numSamples) / numSamples
45+
data = np.fromfile(eegfile, dtype=float).reshape((n_samples, n_rows))
46+
t = 10 * np.arange(n_samples) / n_samples
4847

4948
# Plot the EEG
5049
ticklocs = []
@@ -55,15 +54,15 @@
5554
dmax = data.max()
5655
dr = (dmax - dmin) * 0.7 # Crowd them a bit.
5756
y0 = dmin
58-
y1 = (numRows - 1) * dr + dmax
57+
y1 = (n_rows - 1) * dr + dmax
5958
ax2.set_ylim(y0, y1)
6059

6160
segs = []
62-
for i in range(numRows):
63-
segs.append(np.hstack((t[:, np.newaxis], data[:, i, np.newaxis])))
61+
for i in range(n_rows):
62+
segs.append(np.column_stack((t, data[:, i])))
6463
ticklocs.append(i * dr)
6564

66-
offsets = np.zeros((numRows, 2), dtype=float)
65+
offsets = np.zeros((n_rows, 2), dtype=float)
6766
offsets[:, 1] = ticklocs
6867

6968
lines = LineCollection(segs, offsets=offsets, transOffset=None)

examples/statistics/boxplot_demo.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
center = np.ones(25) * 50
2424
flier_high = np.random.rand(10) * 100 + 100
2525
flier_low = np.random.rand(10) * -100
26-
data = np.concatenate((spread, center, flier_high, flier_low), 0)
26+
data = np.concatenate((spread, center, flier_high, flier_low))
2727

2828
fig, axs = plt.subplots(2, 3)
2929

@@ -59,7 +59,7 @@
5959
center = np.ones(25) * 40
6060
flier_high = np.random.rand(10) * 100 + 100
6161
flier_low = np.random.rand(10) * -100
62-
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)
62+
d2 = np.concatenate((spread, center, flier_high, flier_low))
6363
data.shape = (-1, 1)
6464
d2.shape = (-1, 1)
6565
# Making a 2-D array only works if all the columns are the

lib/matplotlib/axes/_axes.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5732,26 +5732,20 @@ def pcolor(self, *args, **kwargs):
57325732
# don't plot if C or any of the surrounding vertices are masked.
57335733
mask = ma.getmaskarray(C) + xymask
57345734

5735-
newaxis = np.newaxis
57365735
compress = np.compress
57375736

57385737
ravelmask = (mask == 0).ravel()
5739-
X1 = compress(ravelmask, ma.filled(X[0:-1, 0:-1]).ravel())
5740-
Y1 = compress(ravelmask, ma.filled(Y[0:-1, 0:-1]).ravel())
5741-
X2 = compress(ravelmask, ma.filled(X[1:, 0:-1]).ravel())
5742-
Y2 = compress(ravelmask, ma.filled(Y[1:, 0:-1]).ravel())
5738+
X1 = compress(ravelmask, ma.filled(X[:-1, :-1]).ravel())
5739+
Y1 = compress(ravelmask, ma.filled(Y[:-1, :-1]).ravel())
5740+
X2 = compress(ravelmask, ma.filled(X[1:, :-1]).ravel())
5741+
Y2 = compress(ravelmask, ma.filled(Y[1:, :-1]).ravel())
57435742
X3 = compress(ravelmask, ma.filled(X[1:, 1:]).ravel())
57445743
Y3 = compress(ravelmask, ma.filled(Y[1:, 1:]).ravel())
5745-
X4 = compress(ravelmask, ma.filled(X[0:-1, 1:]).ravel())
5746-
Y4 = compress(ravelmask, ma.filled(Y[0:-1, 1:]).ravel())
5744+
X4 = compress(ravelmask, ma.filled(X[:-1, 1:]).ravel())
5745+
Y4 = compress(ravelmask, ma.filled(Y[:-1, 1:]).ravel())
57475746
npoly = len(X1)
57485747

5749-
xy = np.concatenate((X1[:, newaxis], Y1[:, newaxis],
5750-
X2[:, newaxis], Y2[:, newaxis],
5751-
X3[:, newaxis], Y3[:, newaxis],
5752-
X4[:, newaxis], Y4[:, newaxis],
5753-
X1[:, newaxis], Y1[:, newaxis]),
5754-
axis=1)
5748+
xy = np.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)
57555749
verts = xy.reshape((npoly, 5, 2))
57565750

57575751
C = compress(ravelmask, ma.filled(C[0:Ny - 1, 0:Nx - 1]).ravel())

lib/matplotlib/axes/_base.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -341,8 +341,7 @@ def _makefill(self, x, y, kw, kwargs):
341341
# modify the kwargs dictionary.
342342
self._setdefaults(default_dict, kwargs)
343343

344-
seg = mpatches.Polygon(np.hstack((x[:, np.newaxis],
345-
y[:, np.newaxis])),
344+
seg = mpatches.Polygon(np.column_stack((x, y)),
346345
facecolor=facecolor,
347346
fill=kwargs.get('fill', True),
348347
closed=kw['closed'])

lib/matplotlib/collections.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1781,11 +1781,9 @@ def convert_mesh_to_paths(tri):
17811781
17821782
This function is primarily of use to backend implementers.
17831783
"""
1784-
Path = mpath.Path
17851784
triangles = tri.get_masked_triangles()
1786-
verts = np.concatenate((tri.x[triangles][..., np.newaxis],
1787-
tri.y[triangles][..., np.newaxis]), axis=2)
1788-
return [Path(x) for x in verts]
1785+
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
1786+
return [mpath.Path(x) for x in verts]
17891787

17901788
@artist.allow_rasterization
17911789
def draw(self, renderer):
@@ -1798,8 +1796,7 @@ def draw(self, renderer):
17981796
tri = self._triangulation
17991797
triangles = tri.get_masked_triangles()
18001798

1801-
verts = np.concatenate((tri.x[triangles][..., np.newaxis],
1802-
tri.y[triangles][..., np.newaxis]), axis=2)
1799+
verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
18031800

18041801
self.update_scalarmappable()
18051802
colors = self._facecolors[triangles]
@@ -1880,22 +1877,19 @@ def convert_mesh_to_paths(meshWidth, meshHeight, coordinates):
18801877
18811878
This function is primarily of use to backend implementers.
18821879
"""
1883-
Path = mpath.Path
1884-
18851880
if isinstance(coordinates, np.ma.MaskedArray):
18861881
c = coordinates.data
18871882
else:
18881883
c = coordinates
1889-
18901884
points = np.concatenate((
1891-
c[0:-1, 0:-1],
1892-
c[0:-1, 1:],
1885+
c[:-1, :-1],
1886+
c[:-1, 1:],
18931887
c[1:, 1:],
1894-
c[1:, 0:-1],
1895-
c[0:-1, 0:-1]
1888+
c[1:, :-1],
1889+
c[:-1, :-1]
18961890
), axis=2)
18971891
points = points.reshape((meshWidth * meshHeight, 5, 2))
1898-
return [Path(x) for x in points]
1892+
return [mpath.Path(x) for x in points]
18991893

19001894
def convert_mesh_to_triangles(self, meshWidth, meshHeight, coordinates):
19011895
"""

lib/matplotlib/lines.py

Lines changed: 17 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -162,49 +162,38 @@ def _slice_or_none(in_v, slc):
162162
_slice_or_none(codes, slice(start, None, step)))
163163

164164
elif isinstance(step, float):
165-
if not (isinstance(start, int) or
166-
isinstance(start, float)):
167-
raise ValueError('`markevery` is a tuple with '
168-
'len 2 and second element is a float, but '
169-
'the first element is not a float or an '
170-
'int; '
165+
if not isinstance(start, (int, float)):
166+
raise ValueError(
167+
'`markevery` is a tuple with len 2 and second element is '
168+
'a float, but the first element is not a float or an int; '
171169
'markevery=%s' % (markevery,))
172-
#calc cumulative distance along path (in display
173-
# coords):
170+
# calc cumulative distance along path (in display coords):
174171
disp_coords = affine.transform(tpath.vertices)
175-
delta = np.empty((len(disp_coords), 2),
176-
dtype=float)
177-
delta[0, :] = 0.0
178-
delta[1:, :] = (disp_coords[1:, :] -
179-
disp_coords[:-1, :])
172+
delta = np.empty((len(disp_coords), 2))
173+
delta[0, :] = 0
174+
delta[1:, :] = disp_coords[1:, :] - disp_coords[:-1, :]
180175
delta = np.sum(delta**2, axis=1)
181176
delta = np.sqrt(delta)
182177
delta = np.cumsum(delta)
183-
#calc distance between markers along path based on
184-
# the axes bounding box diagonal being a distance
185-
# of unity:
186-
scale = ax_transform.transform(
187-
np.array([[0, 0], [1, 1]]))
178+
# calc distance between markers along path based on the axes
179+
# bounding box diagonal being a distance of unity:
180+
scale = ax_transform.transform(np.array([[0, 0], [1, 1]]))
188181
scale = np.diff(scale, axis=0)
189182
scale = np.sum(scale**2)
190183
scale = np.sqrt(scale)
191-
marker_delta = np.arange(start * scale,
192-
delta[-1],
193-
step * scale)
194-
#find closest actual data point that is closest to
184+
marker_delta = np.arange(start * scale, delta[-1], step * scale)
185+
# find closest actual data point that is closest to
195186
# the theoretical distance along the path:
196-
inds = np.abs(delta[np.newaxis, :] -
197-
marker_delta[:, np.newaxis])
187+
inds = np.abs(delta[np.newaxis, :] - marker_delta[:, np.newaxis])
198188
inds = inds.argmin(axis=1)
199189
inds = np.unique(inds)
200190
# return, we are done here
201191
return Path(verts[inds],
202192
_slice_or_none(codes, inds))
203193
else:
204-
raise ValueError('`markevery` is a tuple with '
205-
'len 2, but its second element is not an int '
206-
'or a float; '
207-
'markevery=%s' % (markevery,))
194+
raise ValueError(
195+
'`markevery` is a tuple with len 2, but its second element is '
196+
'not an int or a float; markevery=%s' % (markevery,))
208197

209198
elif isinstance(markevery, slice):
210199
# mazol tov, it's already a slice, just return

lib/matplotlib/path.py

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -644,22 +644,20 @@ def unit_rectangle(cls):
644644
@classmethod
645645
def unit_regular_polygon(cls, numVertices):
646646
"""
647-
Return a :class:`Path` instance for a unit regular
648-
polygon with the given *numVertices* and radius of 1.0,
649-
centered at (0, 0).
647+
Return a :class:`Path` instance for a unit regular polygon with the
648+
given *numVertices* and radius of 1.0, centered at (0, 0).
650649
"""
651650
if numVertices <= 16:
652651
path = cls._unit_regular_polygons.get(numVertices)
653652
else:
654653
path = None
655654
if path is None:
656-
theta = (2*np.pi/numVertices *
657-
np.arange(numVertices + 1).reshape((numVertices + 1, 1)))
658-
# This initial rotation is to make sure the polygon always
659-
# "points-up"
660-
theta += np.pi / 2.0
661-
verts = np.concatenate((np.cos(theta), np.sin(theta)), 1)
662-
codes = np.empty((numVertices + 1,))
655+
theta = ((2 * np.pi / numVertices) * np.arange(numVertices + 1)
656+
# This initial rotation is to make sure the polygon always
657+
# "points-up".
658+
+ np.pi / 2)
659+
verts = np.column_stack((np.cos(theta), np.sin(theta)))
660+
codes = np.empty(numVertices + 1)
663661
codes[0] = cls.MOVETO
664662
codes[1:-1] = cls.LINETO
665663
codes[-1] = cls.CLOSEPOLY
@@ -673,9 +671,8 @@ def unit_regular_polygon(cls, numVertices):
673671
@classmethod
674672
def unit_regular_star(cls, numVertices, innerCircle=0.5):
675673
"""
676-
Return a :class:`Path` for a unit regular star
677-
with the given numVertices and radius of 1.0, centered at (0,
678-
0).
674+
Return a :class:`Path` for a unit regular star with the given
675+
numVertices and radius of 1.0, centered at (0, 0).
679676
"""
680677
if numVertices <= 16:
681678
path = cls._unit_regular_stars.get((numVertices, innerCircle))
@@ -702,9 +699,8 @@ def unit_regular_star(cls, numVertices, innerCircle=0.5):
702699
@classmethod
703700
def unit_regular_asterisk(cls, numVertices):
704701
"""
705-
Return a :class:`Path` for a unit regular
706-
asterisk with the given numVertices and radius of 1.0,
707-
centered at (0, 0).
702+
Return a :class:`Path` for a unit regular asterisk with the given
703+
numVertices and radius of 1.0, centered at (0, 0).
708704
"""
709705
return cls.unit_regular_star(numVertices, 0.0)
710706

0 commit comments

Comments
 (0)