Skip to content

Commit 75512c5

Browse files
committed
Use np.full{,_like} where appropriate.
1 parent 9b48fd8 commit 75512c5

25 files changed

+45
-51
lines changed

examples/animation/animated_histogram.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@
4545
# in the ``verts`` array to keep the codes aligned with the vertices.
4646
nverts = nrects * (1 + 3 + 1)
4747
verts = np.zeros((nverts, 2))
48-
codes = np.ones(nverts, int) * path.Path.LINETO
48+
codes = np.full(nverts, path.Path.LINETO)
4949
codes[0::5] = path.Path.MOVETO
5050
codes[4::5] = path.Path.CLOSEPOLY
5151
verts[0::5, 0] = left

examples/api/donut.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,7 @@ def make_circle(r):
3232

3333
inside_vertices = make_circle(0.5)
3434
outside_vertices = make_circle(1.0)
35-
codes = np.ones(
36-
len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
35+
codes = np.full(len(inside_vertices), mpath.Path.LINETO)
3736
codes[0] = mpath.Path.MOVETO
3837

3938
for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):

examples/api/filled_step.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ def filled_hist(ax, edges, values, bottoms=None, orientation='v',
6363
if bottoms is None:
6464
bottoms = np.zeros_like(values)
6565
if np.isscalar(bottoms):
66-
bottoms = np.ones_like(values) * bottoms
66+
bottoms = np.full_like(values, bottoms)
6767

6868
values = np.r_[values, values[-1]]
6969
bottoms = np.r_[bottoms, bottoms[-1]]

examples/mplot3d/hist3d.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,7 @@
2929
zpos = np.zeros_like(xpos)
3030

3131
# Construct arrays with the dimensions for the 16 bars.
32-
dx = 0.5 * np.ones_like(zpos)
33-
dy = dx.copy()
32+
dx = dy = np.full_like(zpos, .5)
3433
dz = hist.flatten()
3534

3635
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')

examples/pyplots/boxplot_demo_pyplot.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
# fake up some data
1616
spread = np.random.rand(50) * 100
17-
center = np.ones(25) * 50
17+
center = np.full(25, 50)
1818
flier_high = np.random.rand(10) * 100 + 100
1919
flier_low = np.random.rand(10) * -100
2020
data = np.concatenate((spread, center, flier_high, flier_low), 0)
@@ -61,7 +61,7 @@
6161
# Fake up some more data
6262

6363
spread = np.random.rand(50) * 100
64-
center = np.ones(25) * 40
64+
center = np.full(25, 40)
6565
flier_high = np.random.rand(10) * 100 + 100
6666
flier_low = np.random.rand(10) * -100
6767
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)

examples/pyplots/compound_path_demo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929

3030
nverts = nrects*(1+3+1)
3131
verts = np.zeros((nverts, 2))
32-
codes = np.ones(nverts, int) * path.Path.LINETO
32+
codes = np.full(nverts, path.Path.LINETO)
3333
codes[0::5] = path.Path.MOVETO
3434
codes[4::5] = path.Path.CLOSEPOLY
3535
verts[0::5,0] = left

examples/specialty_plots/leftventricle_bulleye.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
7878
# First segment start at 60 degrees
7979
theta0 = theta[i * 128:i * 128 + 128] + np.deg2rad(60)
8080
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
81-
z = np.ones((128, 2)) * data[i]
81+
z = np.full((128, 2), data[i])
8282
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
8383
if i + 1 in segBold:
8484
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
@@ -92,7 +92,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
9292
# First segment start at 60 degrees
9393
theta0 = theta[i * 128:i * 128 + 128] + np.deg2rad(60)
9494
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
95-
z = np.ones((128, 2)) * data[i + 6]
95+
z = np.full((128, 2), data[i + 6])
9696
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
9797
if i + 7 in segBold:
9898
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
@@ -106,7 +106,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
106106
# First segment start at 45 degrees
107107
theta0 = theta[i * 192:i * 192 + 192] + np.deg2rad(45)
108108
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
109-
z = np.ones((192, 2)) * data[i + 12]
109+
z = np.full((192, 2), data[i + 12])
110110
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
111111
if i + 13 in segBold:
112112
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
@@ -118,7 +118,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
118118
r0 = np.array([0, r[0]])
119119
r0 = np.repeat(r0[:, np.newaxis], theta.size, axis=1).T
120120
theta0 = np.repeat(theta[:, np.newaxis], 2, axis=1)
121-
z = np.ones((theta.size, 2)) * data[16]
121+
z = np.full((theta.size, 2), data[16])
122122
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
123123
if 17 in segBold:
124124
ax.plot(theta0, r0, '-k', lw=linewidth + 2)

examples/statistics/boxplot_demo.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020

2121
# fake up some data
2222
spread = np.random.rand(50) * 100
23-
center = np.ones(25) * 50
23+
center = np.full(25, 50)
2424
flier_high = np.random.rand(10) * 100 + 100
2525
flier_low = np.random.rand(10) * -100
2626
data = np.concatenate((spread, center, flier_high, flier_low), 0)
@@ -56,7 +56,7 @@
5656

5757
# fake up some more data
5858
spread = np.random.rand(50) * 100
59-
center = np.ones(25) * 40
59+
center = np.full(25, 40)
6060
flier_high = np.random.rand(10) * 100 + 100
6161
flier_low = np.random.rand(10) * -100
6262
d2 = np.concatenate((spread, center, flier_high, flier_low), 0)

examples/text_labels_and_annotations/legend_demo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ def create_artists(self, legend, orig_handle,
135135
leglines = []
136136
# divide the vertical space where the lines will go
137137
# into equal parts based on the number of lines
138-
ydata = ((height) / (numlines + 1)) * np.ones(xdata.shape, float)
138+
ydata = np.full_like(xdata, height / (numlines + 1))
139139
# for each line, create the line at the proper location
140140
# and set the dash pattern
141141
for i in range(numlines):

lib/matplotlib/axes/_axes.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -3958,16 +3958,16 @@ def dopatch(xs, ys, **kwargs):
39583958
datalabels.append(stats.get('label', pos))
39593959

39603960
# whisker coords
3961-
whisker_x = np.ones(2) * pos
3961+
whisker_x = np.full(2, pos)
39623962
whiskerlo_y = np.array([stats['q1'], stats['whislo']])
39633963
whiskerhi_y = np.array([stats['q3'], stats['whishi']])
39643964

39653965
# cap coords
39663966
cap_left = pos - width * 0.25
39673967
cap_right = pos + width * 0.25
39683968
cap_x = np.array([cap_left, cap_right])
3969-
cap_lo = np.ones(2) * stats['whislo']
3970-
cap_hi = np.ones(2) * stats['whishi']
3969+
cap_lo = np.full(2, stats['whislo'])
3970+
cap_hi = np.full(2, stats['whishi'])
39713971

39723972
# box and median coords
39733973
box_left = pos - width * 0.5
@@ -4030,7 +4030,7 @@ def dopatch(xs, ys, **kwargs):
40304030
# maybe draw the fliers
40314031
if showfliers:
40324032
# fliers coords
4033-
flier_x = np.ones(len(stats['fliers'])) * pos
4033+
flier_x = np.full(len(stats['fliers']), pos)
40344034
flier_y = stats['fliers']
40354035

40364036
fliers.extend(doplot(

lib/matplotlib/collections.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -979,8 +979,8 @@ def set_verts(self, verts, closed=True):
979979
else:
980980
xy = np.asarray(xy)
981981
xy = np.concatenate([xy, xy[0:1]])
982-
codes = np.empty(xy.shape[0], dtype=mpath.Path.code_type)
983-
codes[:] = mpath.Path.LINETO
982+
codes = np.full(xy.shape[0], mpath.Path.LINETO,
983+
dtype=mpath.Path.code_type)
984984
codes[0] = mpath.Path.MOVETO
985985
codes[-1] = mpath.Path.CLOSEPOLY
986986
self._paths.append(mpath.Path(xy, codes))

lib/matplotlib/hatch.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ def __init__(self, hatch, density):
174174
self.num_rows = (hatch.count('*')) * density
175175
path = Path.unit_regular_star(5)
176176
self.shape_vertices = path.vertices
177-
self.shape_codes = np.ones(len(self.shape_vertices)) * Path.LINETO
177+
self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO)
178178
self.shape_codes[0] = Path.MOVETO
179179
Shapes.__init__(self, hatch, density)
180180

lib/matplotlib/legend_handler.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ def create_artists(self, legend, orig_handle,
235235
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
236236
width, height, fontsize)
237237

238-
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
238+
ydata = np.full_like(xdata, (height - ydescent) / 2)
239239
legline = Line2D(xdata, ydata)
240240

241241
self.update_prop(legline, orig_handle, legend)
@@ -328,7 +328,7 @@ def create_artists(self, legend, orig_handle,
328328

329329
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
330330
width, height, fontsize)
331-
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
331+
ydata = np.full_like(xdata, (height - ydescent) / 2)
332332
legline = Line2D(xdata, ydata)
333333

334334
self.update_prop(legline, orig_handle, legend)
@@ -470,7 +470,7 @@ def create_artists(self, legend, orig_handle,
470470
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
471471
width, height, fontsize)
472472

473-
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
473+
ydata = np.full_like(xdata, (height - ydescent) / 2)
474474
legline = Line2D(xdata, ydata)
475475

476476
xdata_marker = np.asarray(xdata_marker)

lib/matplotlib/path.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -321,10 +321,10 @@ def make_compound_path_from_polys(cls, XY):
321321
raise ValueError("The third dimension of 'XY' must be 2")
322322
stride = numsides + 1
323323
nverts = numpolys * stride
324-
verts = np.zeros((nverts, 2))
325-
codes = np.ones(nverts, int) * cls.LINETO
324+
codes = np.full(nverts, cls.LINETO)
326325
codes[0::stride] = cls.MOVETO
327326
codes[numsides::stride] = cls.CLOSEPOLY
327+
verts = np.zeros((nverts, 2))
328328
for i in range(numsides):
329329
verts[i::stride] = XY[:, i]
330330

@@ -572,7 +572,7 @@ def interpolated(self, steps):
572572
vertices = simple_linear_interpolation(self.vertices, steps)
573573
codes = self.codes
574574
if codes is not None:
575-
new_codes = Path.LINETO * np.ones(((len(codes) - 1) * steps + 1, ))
575+
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO)
576576
new_codes[0::steps] = codes
577577
else:
578578
new_codes = None
@@ -896,17 +896,17 @@ def arc(cls, theta1, theta2, n=None, is_wedge=False):
896896

897897
if is_wedge:
898898
length = n * 3 + 4
899-
vertices = np.zeros((length, 2), float)
900-
codes = cls.CURVE4 * np.ones((length, ), cls.code_type)
899+
vertices = np.zeros((length, 2))
900+
codes = np.full(length, cls.CURVE4, cls.code_type)
901901
vertices[1] = [xA[0], yA[0]]
902902
codes[0:2] = [cls.MOVETO, cls.LINETO]
903903
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
904904
vertex_offset = 2
905905
end = length - 2
906906
else:
907907
length = n * 3 + 1
908-
vertices = np.empty((length, 2), float)
909-
codes = cls.CURVE4 * np.ones((length, ), cls.code_type)
908+
vertices = np.empty((length, 2))
909+
codes = np.full(length, cls.CURVE4, cls.code_type)
910910
vertices[0] = [xA[0], yA[0]]
911911
codes[0] = cls.MOVETO
912912
vertex_offset = 1

lib/matplotlib/tests/test_axes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1511,7 +1511,7 @@ def test_hist_steplog():
15111511
data += -2.0 - np.min(data)
15121512
data_pos = data + 2.1
15131513
data_big = data_pos + 30
1514-
weights = np.ones_like(data) * 1.e-5
1514+
weights = np.full_like(data, 1e-5)
15151515

15161516
ax = plt.subplot(4, 1, 1)
15171517
plt.hist(data, 100, histtype='stepfilled', log=True)
@@ -4931,7 +4931,7 @@ def test_violin_point_mass():
49314931

49324932

49334933
def generate_errorbar_inputs():
4934-
base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones((5, ))])
4934+
base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones(5)])
49354935
err_cycler = cycler('err', [1,
49364936
[1, 1, 1, 1, 1],
49374937
[[1, 1, 1, 1, 1],

lib/matplotlib/tests/test_collections.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -454,7 +454,7 @@ def test_EllipseCollection():
454454

455455
ww = X / x[-1]
456456
hh = Y / y[-1]
457-
aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis
457+
aa = np.full_like(ww, 20) # first axis is 20 degrees CCW from x axis
458458

459459
ec = mcollections.EllipseCollection(ww, hh, aa,
460460
units='x',

lib/matplotlib/tests/test_image.py

+1-4
Original file line numberDiff line numberDiff line change
@@ -896,12 +896,9 @@ def test_imshow_deprecated_interd_warn():
896896

897897

898898
def test_full_invalid():
899-
x = np.ones((10, 10))
900-
x[:] = np.nan
901-
899+
x = np.full((10, 10), np.nan)
902900
f, ax = plt.subplots()
903901
ax.imshow(x)
904-
905902
f.canvas.draw()
906903

907904

lib/matplotlib/tests/test_legend.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def test_labels_first():
124124
fig = plt.figure()
125125
ax = fig.add_subplot(111)
126126
ax.plot(np.arange(10), '-o', label=1)
127-
ax.plot(np.ones(10)*5, ':x', label="x")
127+
ax.plot(np.full(10, 5), ':x', label="x")
128128
ax.plot(np.arange(20, 10, -1), 'd', label="diamond")
129129
ax.legend(loc=0, markerfirst=False)
130130

lib/matplotlib/tests/test_lines.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def test_lw_scaling():
189189
cy = cycler(matplotlib.rcParams['axes.prop_cycle'])
190190
for j, (ls, sty) in enumerate(zip(lins_styles, cy)):
191191
for lw in np.linspace(.5, 10, 10):
192-
ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)
192+
ax.plot(th, np.full(50, j) + .1 * lw, linestyle=ls, lw=lw, **sty)
193193

194194

195195
def test_nan_is_sorted():

lib/matplotlib/tests/test_path.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ def test_marker_paths_pdf():
123123
N = 7
124124

125125
plt.errorbar(np.arange(N),
126-
np.ones(N) + 4,
126+
np.full(N, 5),
127127
np.ones(N))
128128
plt.xlim(-1, N)
129129
plt.ylim(-1, 7)

lib/matplotlib/tests/test_quiver.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,8 @@ def test_bad_masked_sizes():
158158
'Test error handling when given differing sized masked arrays'
159159
x = np.arange(3)
160160
y = np.arange(3)
161-
u = np.ma.array(15. * np.ones((4,)))
162-
v = np.ma.array(15. * np.ones_like(u))
161+
u = np.ma.array(np.full(4, 15.))
162+
v = np.ma.array(np.full(4, 15.))
163163
u[1] = np.ma.masked
164164
v[1] = np.ma.masked
165165
fig, ax = plt.subplots()

lib/matplotlib/tests/test_triangulation.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -645,7 +645,7 @@ def test_triinterp_colinear():
645645
zs_target = 1.23*xs - 4.79*ys
646646
for interp in (linear_interp, cubic_min_E, cubic_geom):
647647
zs, = interp._interpolate_multikeys(
648-
xs, ys, tri_index=itri*np.ones(10, dtype=np.int32))
648+
xs, ys, tri_index=np.full(10, itri, dtype=np.int32))
649649
assert_array_almost_equal(zs_target, zs)
650650

651651

lib/matplotlib/text.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -335,8 +335,7 @@ def _get_layout(self, renderer):
335335
# get the rotation matrix
336336
M = Affine2D().rotate_deg(self.get_rotation())
337337

338-
offsetLayout = np.zeros((len(lines), 2))
339-
offsetLayout[:] = horizLayout[:, 0:2]
338+
offsetLayout = horizLayout[:, 0:2].copy()
340339
# now offset the individual text lines within the box
341340
if len(lines) > 1: # do the multiline aligment
342341
malign = self._get_multialignment()

lib/matplotlib/tri/triinterpolate.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -684,7 +684,7 @@ class _ReducedHCT_Element():
684684
[ 4./18., 1./18., 13./18.],
685685
[13./18., 1./18., 4./18.],
686686
[ 7./18., 4./18., 7./18.]], dtype=np.float64)
687-
gauss_w = np.ones([9], dtype=np.float64) / 9.
687+
gauss_w = np.full(9, 1 / 9)
688688

689689
# 4) Stiffness matrix for curvature energy
690690
E = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 2.]])

tutorials/advanced/path_tutorial.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@
158158
#
159159
# nverts = nrects*(1+3+1)
160160
# verts = np.zeros((nverts, 2))
161-
# codes = np.ones(nverts, int) * path.Path.LINETO
161+
# codes = np.full(nverts, path.Path.LINETO)
162162
# codes[0::5] = path.Path.MOVETO
163163
# codes[4::5] = path.Path.CLOSEPOLY
164164
# verts[0::5,0] = left
@@ -201,7 +201,7 @@
201201

202202
nverts = nrects*(1+3+1)
203203
verts = np.zeros((nverts, 2))
204-
codes = np.ones(nverts, int) * path.Path.LINETO
204+
codes = np.full(nverts, path.Path.LINETO)
205205
codes[0::5] = path.Path.MOVETO
206206
codes[4::5] = path.Path.CLOSEPOLY
207207
verts[0::5, 0] = left

0 commit comments

Comments
 (0)