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

Skip to content

Commit b5155b7

Browse files
committed
Remove unnecessary calls to np.array in examples.
There's many places where explicit conversion to np.array is not necessary -- because matplotlib or numpy already handles the conversion, or because the variable is already an array. Removing these calls makes the examples concentrate more on the plotting-relevant parts.
1 parent b2e6e6d commit b5155b7

File tree

20 files changed

+54
-58
lines changed

20 files changed

+54
-58
lines changed

examples/animation/animated_histogram.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
n, bins = np.histogram(data, 100)
2222

2323
# get the corners of the rectangles for the histogram
24-
left = np.array(bins[:-1])
25-
right = np.array(bins[1:])
24+
left = bins[:-1]
25+
right = bins[1:]
2626
bottom = np.zeros(len(left))
2727
top = bottom + n
2828
nrects = len(left)

examples/images_contours_and_fields/image_annotated_heatmap.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ def annotate_heatmap(im, data=None, valfmt="{x:.2f}",
271271
y = ["Prod. {}".format(i) for i in range(10, 70, 10)]
272272
x = ["Cycle {}".format(i) for i in range(1, 7)]
273273

274-
qrates = np.array(list("ABCDEFG"))
274+
qrates = list("ABCDEFG")
275275
norm = matplotlib.colors.BoundaryNorm(np.linspace(-3.5, 3.5, 8), 7)
276276
fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: qrates[::-1][norm(x)])
277277

examples/lines_bars_and_markers/eventplot_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424

2525
# set different line properties for each set of positions
2626
# note that some overlap
27-
lineoffsets1 = np.array([-15, -3, 1, 1.5, 6, 10])
27+
lineoffsets1 = [-15, -3, 1, 1.5, 6, 10]
2828
linelengths1 = [5, 2, 1, 1, 3, 1.5]
2929

3030
fig, axs = plt.subplots(2, 2)

examples/lines_bars_and_markers/scatter_star_poly.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
axs[0, 1].set_title(r"marker=r'\$\alpha\$'")
2929

3030
# marker from path
31-
verts = np.array([[-1, -1], [1, -1], [1, 1], [-1, -1]])
31+
verts = [[-1, -1], [1, -1], [1, 1], [-1, -1]]
3232
axs[0, 2].scatter(x, y, s=80, c=z, marker=verts)
3333
axs[0, 2].set_title("marker=verts")
3434

examples/lines_bars_and_markers/timeline.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,11 @@
8181
markerline.set_ydata(np.zeros(len(dates)))
8282

8383
# annotate lines
84-
vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)]
85-
for d, l, r, va in zip(dates, levels, names, vert):
86-
ax.annotate(r, xy=(d, l), xytext=(-3, np.sign(l)*3),
87-
textcoords="offset points", va=va, ha="right")
84+
for d, l, r in zip(dates, levels, names):
85+
ax.annotate(r, xy=(d, l),
86+
xytext=(-3, np.sign(l)*3), textcoords="offset points",
87+
horizontalalignment="right",
88+
verticalalignment="bottom" if l > 0 else "top")
8889

8990
# format xaxis with 4 month intervals
9091
ax.get_xaxis().set_major_locator(mdates.MonthLocator(interval=4))

examples/misc/histogram_path.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@
3131
n, bins = np.histogram(data, 50)
3232

3333
# get the corners of the rectangles for the histogram
34-
left = np.array(bins[:-1])
35-
right = np.array(bins[1:])
34+
left = bins[:-1]
35+
right = bins[1:]
3636
bottom = np.zeros(len(left))
3737
top = bottom + n
3838

examples/pie_and_polar_charts/nested_pie.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232

3333
cmap = plt.get_cmap("tab20c")
3434
outer_colors = cmap(np.arange(3)*4)
35-
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
35+
inner_colors = cmap([1, 2, 5, 6, 9, 10])
3636

3737
ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
3838
wedgeprops=dict(width=size, edgecolor='w'))
@@ -63,7 +63,7 @@
6363

6464
cmap = plt.get_cmap("tab20c")
6565
outer_colors = cmap(np.arange(3)*4)
66-
inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
66+
inner_colors = cmap([1, 2, 5, 6, 9, 10])
6767

6868
ax.bar(x=valsleft[:, 0],
6969
width=valsnorm.sum(axis=1), bottom=1-size, height=size,

examples/scales/logit_demo.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,17 @@
66
Examples of plots with logit axes.
77
"""
88

9+
import math
10+
911
import numpy as np
1012
import matplotlib.pyplot as plt
1113

1214
xmax = 10
1315
x = np.linspace(-xmax, xmax, 10000)
14-
cdf_norm = np.array([np.math.erf(w / np.sqrt(2)) / 2 + 1 / 2 for w in x])
15-
cdf_laplacian = np.array(
16-
[1 / 2 * np.exp(w) if w < 0 else 1 - 1 / 2 * np.exp(-w) for w in x]
17-
)
18-
cdf_cauchy = 1 / np.pi * np.arctan(x) + 1 / 2
16+
cdf_norm = [math.erf(w / np.sqrt(2)) / 2 + 1 / 2 for w in x]
17+
cdf_laplacian = [1 / 2 * np.exp(w) if w < 0 else 1 - 1 / 2 * np.exp(-w)
18+
for w in x]
19+
cdf_cauchy = np.arctan(x) / np.pi + 1 / 2
1920

2021
fig, axs = plt.subplots(nrows=3, ncols=2, figsize=(6.4, 8.5))
2122

examples/shapes_and_collections/artist_reference.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,13 @@ def label(xy, text):
8686
label(grid[7], "FancyBboxPatch")
8787

8888
# add a line
89-
x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]])
89+
x, y = ([-0.06, 0.0, 0.1], [0.05, -0.05, 0.05])
9090
line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3)
9191
label(grid[8], "Line2D")
9292

9393
colors = np.linspace(0, 1, len(patches))
9494
collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3)
95-
collection.set_array(np.array(colors))
95+
collection.set_array(colors)
9696
ax.add_collection(collection)
9797
ax.add_line(line)
9898

examples/shapes_and_collections/compound_path.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,11 @@
77
and a triangle. Use ``CLOSEPOLY`` and ``MOVETO`` for the different parts of
88
the compound path
99
"""
10-
import numpy as np
10+
1111
from matplotlib.path import Path
1212
from matplotlib.patches import PathPatch
1313
import matplotlib.pyplot as plt
1414

15-
1615
vertices = []
1716
codes = []
1817

@@ -22,7 +21,6 @@
2221
codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]
2322
vertices += [(4, 4), (5, 5), (5, 4), (0, 0)]
2423

25-
vertices = np.array(vertices, float)
2624
path = Path(vertices, codes)
2725

2826
pathpatch = PathPatch(path, facecolor='None', edgecolor='green')

examples/shapes_and_collections/patch_collection.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,9 +48,9 @@
4848
polygon = Polygon(np.random.rand(N, 2), True)
4949
patches.append(polygon)
5050

51-
colors = 100*np.random.rand(len(patches))
51+
colors = 100 * np.random.rand(len(patches))
5252
p = PatchCollection(patches, alpha=0.4)
53-
p.set_array(np.array(colors))
53+
p.set_array(colors)
5454
ax.add_collection(p)
5555
fig.colorbar(p, ax=ax)
5656

examples/specialty_plots/leftventricle_bulleye.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def bullseye_plot(ax, data, seg_bold=None, cmap=None, norm=None):
4646
seg_bold = []
4747

4848
linewidth = 2
49-
data = np.array(data).ravel()
49+
data = np.ravel(data)
5050

5151
if cmap is None:
5252
cmap = plt.cm.viridis
@@ -129,7 +129,7 @@ def bullseye_plot(ax, data, seg_bold=None, cmap=None, norm=None):
129129

130130

131131
# Create the fake data
132-
data = np.array(range(17)) + 1
132+
data = np.arange(17) + 1
133133

134134

135135
# Make a figure and axes with dimensions as desired.

examples/statistics/boxplot_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ def fake_bootstrapper(n):
221221
conf_intervals = [None, None, ci1, ci2]
222222

223223
fig, ax = plt.subplots()
224-
pos = np.array(range(len(treatments))) + 1
224+
pos = np.arange(len(treatments)) + 1
225225
bp = ax.boxplot(treatments, sym='k+', positions=pos,
226226
notch=1, bootstrap=5000,
227227
usermedians=medians,

examples/statistics/confidence_ellipse.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -128,12 +128,12 @@ def get_correlated_dataset(n, dependency, mu, scale):
128128
np.random.seed(0)
129129

130130
PARAMETERS = {
131-
'Positive correlation': np.array([[0.85, 0.35],
132-
[0.15, -0.65]]),
133-
'Negative correlation': np.array([[0.9, -0.4],
134-
[0.1, -0.6]]),
135-
'Weak correlation': np.array([[1, 0],
136-
[0, 1]]),
131+
'Positive correlation': [[0.85, 0.35],
132+
[0.15, -0.65]],
133+
'Negative correlation': [[0.9, -0.4],
134+
[0.1, -0.6]],
135+
'Weak correlation': [[1, 0],
136+
[0, 1]],
137137
}
138138

139139
mu = 2, 4
@@ -164,10 +164,8 @@ def get_correlated_dataset(n, dependency, mu, scale):
164164

165165
fig, ax_nstd = plt.subplots(figsize=(6, 6))
166166

167-
dependency_nstd = np.array([
168-
[0.8, 0.75],
169-
[-0.2, 0.35]
170-
])
167+
dependency_nstd = [[0.8, 0.75],
168+
[-0.2, 0.35]]
171169
mu = 0, 0
172170
scale = 8, 5
173171

@@ -199,10 +197,8 @@ def get_correlated_dataset(n, dependency, mu, scale):
199197
# to have the ellipse rendered in different ways.
200198

201199
fig, ax_kwargs = plt.subplots(figsize=(6, 6))
202-
dependency_kwargs = np.array([
203-
[-0.8, 0.5],
204-
[-0.2, 0.5]
205-
])
200+
dependency_kwargs = [[-0.8, 0.5],
201+
[-0.2, 0.5]]
206202
mu = 2, -3
207203
scale = 6, 5
208204

examples/statistics/errorbar_limits.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,8 +58,8 @@
5858
# mock up some limits by modifying previous data
5959
xlolims = lolims
6060
xuplims = uplims
61-
lolims = np.zeros(x.shape)
62-
uplims = np.zeros(x.shape)
61+
lolims = np.zeros_like(x)
62+
uplims = np.zeros_like(x)
6363
lolims[[6]] = True # only limited at this index
6464
uplims[[3]] = True # only limited at this index
6565

examples/subplots_axes_and_figures/axes_box_aspect.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@
106106
axs[1, 0].set_box_aspect(1)
107107
axs[1, 1].set_box_aspect(3/1)
108108

109-
x, y = np.random.randn(2, 400) * np.array([[.5], [180]])
109+
x, y = np.random.randn(2, 400) * [[.5], [180]]
110110
axs[1, 0].scatter(x, y)
111111
axs[0, 0].hist(x)
112112
axs[1, 1].hist(y, orientation="horizontal")

examples/text_labels_and_annotations/custom_legends.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,8 @@
2727
np.random.seed(19680801)
2828

2929
N = 10
30-
data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)]
31-
data = np.array(data).T
30+
data = np.transpose([np.logspace(0, 1, 100) + np.random.randn(100) + ii
31+
for ii in range(N)])
3232
cmap = plt.cm.coolwarm
3333
rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N)))
3434

examples/text_labels_and_annotations/text_rotation_relative_to_line.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -17,25 +17,26 @@
1717
import matplotlib.pyplot as plt
1818
import numpy as np
1919

20+
fig, ax = plt.subplots()
21+
2022
# Plot diagonal line (45 degrees)
21-
h = plt.plot(np.arange(0, 10), np.arange(0, 10))
23+
h = ax.plot(range(0, 10), range(0, 10))
2224

2325
# set limits so that it no longer looks on screen to be 45 degrees
24-
plt.xlim([-10, 20])
26+
ax.set_xlim([-10, 20])
2527

2628
# Locations to plot text
2729
l1 = np.array((1, 1))
2830
l2 = np.array((5, 5))
2931

3032
# Rotate angle
3133
angle = 45
32-
trans_angle = plt.gca().transData.transform_angles(np.array((45,)),
33-
l2.reshape((1, 2)))[0]
34+
trans_angle = ax.transData.transform_angles([45], l2.reshape((1, 2)))[0]
3435

3536
# Plot text
36-
th1 = plt.text(l1[0], l1[1], 'text not rotated correctly', fontsize=16,
37-
rotation=angle, rotation_mode='anchor')
38-
th2 = plt.text(l2[0], l2[1], 'text rotated correctly', fontsize=16,
39-
rotation=trans_angle, rotation_mode='anchor')
37+
th1 = ax.text(*l1, 'text not rotated correctly', fontsize=16,
38+
rotation=angle, rotation_mode='anchor')
39+
th2 = ax.text(*l2, 'text rotated correctly', fontsize=16,
40+
rotation=trans_angle, rotation_mode='anchor')
4041

4142
plt.show()

examples/ticks_and_spines/date_concise_formatter.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,7 @@
2424
# First, the default formatter.
2525

2626
base = datetime.datetime(2005, 2, 1)
27-
dates = np.array([base + datetime.timedelta(hours=(2 * i))
28-
for i in range(732)])
27+
dates = [base + datetime.timedelta(hours=(2 * i)) for i in range(732)]
2928
N = len(dates)
3029
np.random.seed(19680801)
3130
y = np.cumsum(np.random.randn(N))

examples/units/ellipse_with_units.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
])
3131

3232

33-
x, y = np.dot(R, np.array([x, y]))
33+
x, y = np.dot(R, [x, y])
3434
x += xcenter
3535
y += ycenter
3636

0 commit comments

Comments
 (0)