From b5155b7bf1b03eb6b6b7d4426cb0daec4f5d8fe5 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 6 Feb 2020 23:17:22 +0100 Subject: [PATCH] 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. --- examples/animation/animated_histogram.py | 4 ++-- .../image_annotated_heatmap.py | 2 +- .../lines_bars_and_markers/eventplot_demo.py | 2 +- .../scatter_star_poly.py | 2 +- examples/lines_bars_and_markers/timeline.py | 9 +++---- examples/misc/histogram_path.py | 4 ++-- examples/pie_and_polar_charts/nested_pie.py | 4 ++-- examples/scales/logit_demo.py | 11 +++++---- .../artist_reference.py | 4 ++-- .../shapes_and_collections/compound_path.py | 4 +--- .../patch_collection.py | 4 ++-- .../specialty_plots/leftventricle_bulleye.py | 4 ++-- examples/statistics/boxplot_demo.py | 2 +- examples/statistics/confidence_ellipse.py | 24 ++++++++----------- examples/statistics/errorbar_limits.py | 4 ++-- .../axes_box_aspect.py | 2 +- .../custom_legends.py | 4 ++-- .../text_rotation_relative_to_line.py | 17 ++++++------- .../date_concise_formatter.py | 3 +-- examples/units/ellipse_with_units.py | 2 +- 20 files changed, 54 insertions(+), 58 deletions(-) diff --git a/examples/animation/animated_histogram.py b/examples/animation/animated_histogram.py index fc4e7f2dad69..2df4def04354 100644 --- a/examples/animation/animated_histogram.py +++ b/examples/animation/animated_histogram.py @@ -21,8 +21,8 @@ n, bins = np.histogram(data, 100) # get the corners of the rectangles for the histogram -left = np.array(bins[:-1]) -right = np.array(bins[1:]) +left = bins[:-1] +right = bins[1:] bottom = np.zeros(len(left)) top = bottom + n nrects = len(left) diff --git a/examples/images_contours_and_fields/image_annotated_heatmap.py b/examples/images_contours_and_fields/image_annotated_heatmap.py index 0fef4590223a..3aac185f0e82 100644 --- a/examples/images_contours_and_fields/image_annotated_heatmap.py +++ b/examples/images_contours_and_fields/image_annotated_heatmap.py @@ -271,7 +271,7 @@ def annotate_heatmap(im, data=None, valfmt="{x:.2f}", y = ["Prod. {}".format(i) for i in range(10, 70, 10)] x = ["Cycle {}".format(i) for i in range(1, 7)] -qrates = np.array(list("ABCDEFG")) +qrates = list("ABCDEFG") norm = matplotlib.colors.BoundaryNorm(np.linspace(-3.5, 3.5, 8), 7) fmt = matplotlib.ticker.FuncFormatter(lambda x, pos: qrates[::-1][norm(x)]) diff --git a/examples/lines_bars_and_markers/eventplot_demo.py b/examples/lines_bars_and_markers/eventplot_demo.py index d1be2fbe91f1..2f97606ce32e 100644 --- a/examples/lines_bars_and_markers/eventplot_demo.py +++ b/examples/lines_bars_and_markers/eventplot_demo.py @@ -24,7 +24,7 @@ # set different line properties for each set of positions # note that some overlap -lineoffsets1 = np.array([-15, -3, 1, 1.5, 6, 10]) +lineoffsets1 = [-15, -3, 1, 1.5, 6, 10] linelengths1 = [5, 2, 1, 1, 3, 1.5] fig, axs = plt.subplots(2, 2) diff --git a/examples/lines_bars_and_markers/scatter_star_poly.py b/examples/lines_bars_and_markers/scatter_star_poly.py index 690d7ae3944e..53089c2819a6 100644 --- a/examples/lines_bars_and_markers/scatter_star_poly.py +++ b/examples/lines_bars_and_markers/scatter_star_poly.py @@ -28,7 +28,7 @@ axs[0, 1].set_title(r"marker=r'\$\alpha\$'") # marker from path -verts = np.array([[-1, -1], [1, -1], [1, 1], [-1, -1]]) +verts = [[-1, -1], [1, -1], [1, 1], [-1, -1]] axs[0, 2].scatter(x, y, s=80, c=z, marker=verts) axs[0, 2].set_title("marker=verts") diff --git a/examples/lines_bars_and_markers/timeline.py b/examples/lines_bars_and_markers/timeline.py index 3ef964defe48..7fee6d43a4e0 100644 --- a/examples/lines_bars_and_markers/timeline.py +++ b/examples/lines_bars_and_markers/timeline.py @@ -81,10 +81,11 @@ markerline.set_ydata(np.zeros(len(dates))) # annotate lines -vert = np.array(['top', 'bottom'])[(levels > 0).astype(int)] -for d, l, r, va in zip(dates, levels, names, vert): - ax.annotate(r, xy=(d, l), xytext=(-3, np.sign(l)*3), - textcoords="offset points", va=va, ha="right") +for d, l, r in zip(dates, levels, names): + ax.annotate(r, xy=(d, l), + xytext=(-3, np.sign(l)*3), textcoords="offset points", + horizontalalignment="right", + verticalalignment="bottom" if l > 0 else "top") # format xaxis with 4 month intervals ax.get_xaxis().set_major_locator(mdates.MonthLocator(interval=4)) diff --git a/examples/misc/histogram_path.py b/examples/misc/histogram_path.py index 4eb4d68ba2d5..d93df6b2c863 100644 --- a/examples/misc/histogram_path.py +++ b/examples/misc/histogram_path.py @@ -31,8 +31,8 @@ n, bins = np.histogram(data, 50) # get the corners of the rectangles for the histogram -left = np.array(bins[:-1]) -right = np.array(bins[1:]) +left = bins[:-1] +right = bins[1:] bottom = np.zeros(len(left)) top = bottom + n diff --git a/examples/pie_and_polar_charts/nested_pie.py b/examples/pie_and_polar_charts/nested_pie.py index 7e71eb724b73..d539cb2489c4 100644 --- a/examples/pie_and_polar_charts/nested_pie.py +++ b/examples/pie_and_polar_charts/nested_pie.py @@ -32,7 +32,7 @@ cmap = plt.get_cmap("tab20c") outer_colors = cmap(np.arange(3)*4) -inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10])) +inner_colors = cmap([1, 2, 5, 6, 9, 10]) ax.pie(vals.sum(axis=1), radius=1, colors=outer_colors, wedgeprops=dict(width=size, edgecolor='w')) @@ -63,7 +63,7 @@ cmap = plt.get_cmap("tab20c") outer_colors = cmap(np.arange(3)*4) -inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10])) +inner_colors = cmap([1, 2, 5, 6, 9, 10]) ax.bar(x=valsleft[:, 0], width=valsnorm.sum(axis=1), bottom=1-size, height=size, diff --git a/examples/scales/logit_demo.py b/examples/scales/logit_demo.py index a79060f5ab47..a23b8e28fc0e 100644 --- a/examples/scales/logit_demo.py +++ b/examples/scales/logit_demo.py @@ -6,16 +6,17 @@ Examples of plots with logit axes. """ +import math + import numpy as np import matplotlib.pyplot as plt xmax = 10 x = np.linspace(-xmax, xmax, 10000) -cdf_norm = np.array([np.math.erf(w / np.sqrt(2)) / 2 + 1 / 2 for w in x]) -cdf_laplacian = np.array( - [1 / 2 * np.exp(w) if w < 0 else 1 - 1 / 2 * np.exp(-w) for w in x] -) -cdf_cauchy = 1 / np.pi * np.arctan(x) + 1 / 2 +cdf_norm = [math.erf(w / np.sqrt(2)) / 2 + 1 / 2 for w in x] +cdf_laplacian = [1 / 2 * np.exp(w) if w < 0 else 1 - 1 / 2 * np.exp(-w) + for w in x] +cdf_cauchy = np.arctan(x) / np.pi + 1 / 2 fig, axs = plt.subplots(nrows=3, ncols=2, figsize=(6.4, 8.5)) diff --git a/examples/shapes_and_collections/artist_reference.py b/examples/shapes_and_collections/artist_reference.py index 7a3385b9dbca..d8e267c98d5e 100644 --- a/examples/shapes_and_collections/artist_reference.py +++ b/examples/shapes_and_collections/artist_reference.py @@ -86,13 +86,13 @@ def label(xy, text): label(grid[7], "FancyBboxPatch") # add a line -x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]]) +x, y = ([-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]) line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3) label(grid[8], "Line2D") colors = np.linspace(0, 1, len(patches)) collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3) -collection.set_array(np.array(colors)) +collection.set_array(colors) ax.add_collection(collection) ax.add_line(line) diff --git a/examples/shapes_and_collections/compound_path.py b/examples/shapes_and_collections/compound_path.py index 5667f494001d..ceff94400686 100644 --- a/examples/shapes_and_collections/compound_path.py +++ b/examples/shapes_and_collections/compound_path.py @@ -7,12 +7,11 @@ and a triangle. Use ``CLOSEPOLY`` and ``MOVETO`` for the different parts of the compound path """ -import numpy as np + from matplotlib.path import Path from matplotlib.patches import PathPatch import matplotlib.pyplot as plt - vertices = [] codes = [] @@ -22,7 +21,6 @@ codes += [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY] vertices += [(4, 4), (5, 5), (5, 4), (0, 0)] -vertices = np.array(vertices, float) path = Path(vertices, codes) pathpatch = PathPatch(path, facecolor='None', edgecolor='green') diff --git a/examples/shapes_and_collections/patch_collection.py b/examples/shapes_and_collections/patch_collection.py index fc28eebf1177..33e137edb6a1 100644 --- a/examples/shapes_and_collections/patch_collection.py +++ b/examples/shapes_and_collections/patch_collection.py @@ -48,9 +48,9 @@ polygon = Polygon(np.random.rand(N, 2), True) patches.append(polygon) -colors = 100*np.random.rand(len(patches)) +colors = 100 * np.random.rand(len(patches)) p = PatchCollection(patches, alpha=0.4) -p.set_array(np.array(colors)) +p.set_array(colors) ax.add_collection(p) fig.colorbar(p, ax=ax) diff --git a/examples/specialty_plots/leftventricle_bulleye.py b/examples/specialty_plots/leftventricle_bulleye.py index adb0d53ae202..834d158f1ac0 100644 --- a/examples/specialty_plots/leftventricle_bulleye.py +++ b/examples/specialty_plots/leftventricle_bulleye.py @@ -46,7 +46,7 @@ def bullseye_plot(ax, data, seg_bold=None, cmap=None, norm=None): seg_bold = [] linewidth = 2 - data = np.array(data).ravel() + data = np.ravel(data) if cmap is None: cmap = plt.cm.viridis @@ -129,7 +129,7 @@ def bullseye_plot(ax, data, seg_bold=None, cmap=None, norm=None): # Create the fake data -data = np.array(range(17)) + 1 +data = np.arange(17) + 1 # Make a figure and axes with dimensions as desired. diff --git a/examples/statistics/boxplot_demo.py b/examples/statistics/boxplot_demo.py index 6f1866b62124..4cd99cd07b17 100644 --- a/examples/statistics/boxplot_demo.py +++ b/examples/statistics/boxplot_demo.py @@ -221,7 +221,7 @@ def fake_bootstrapper(n): conf_intervals = [None, None, ci1, ci2] fig, ax = plt.subplots() -pos = np.array(range(len(treatments))) + 1 +pos = np.arange(len(treatments)) + 1 bp = ax.boxplot(treatments, sym='k+', positions=pos, notch=1, bootstrap=5000, usermedians=medians, diff --git a/examples/statistics/confidence_ellipse.py b/examples/statistics/confidence_ellipse.py index 2db715237d57..14c8a15d822e 100644 --- a/examples/statistics/confidence_ellipse.py +++ b/examples/statistics/confidence_ellipse.py @@ -128,12 +128,12 @@ def get_correlated_dataset(n, dependency, mu, scale): np.random.seed(0) PARAMETERS = { - 'Positive correlation': np.array([[0.85, 0.35], - [0.15, -0.65]]), - 'Negative correlation': np.array([[0.9, -0.4], - [0.1, -0.6]]), - 'Weak correlation': np.array([[1, 0], - [0, 1]]), + 'Positive correlation': [[0.85, 0.35], + [0.15, -0.65]], + 'Negative correlation': [[0.9, -0.4], + [0.1, -0.6]], + 'Weak correlation': [[1, 0], + [0, 1]], } mu = 2, 4 @@ -164,10 +164,8 @@ def get_correlated_dataset(n, dependency, mu, scale): fig, ax_nstd = plt.subplots(figsize=(6, 6)) -dependency_nstd = np.array([ - [0.8, 0.75], - [-0.2, 0.35] -]) +dependency_nstd = [[0.8, 0.75], + [-0.2, 0.35]] mu = 0, 0 scale = 8, 5 @@ -199,10 +197,8 @@ def get_correlated_dataset(n, dependency, mu, scale): # to have the ellipse rendered in different ways. fig, ax_kwargs = plt.subplots(figsize=(6, 6)) -dependency_kwargs = np.array([ - [-0.8, 0.5], - [-0.2, 0.5] -]) +dependency_kwargs = [[-0.8, 0.5], + [-0.2, 0.5]] mu = 2, -3 scale = 6, 5 diff --git a/examples/statistics/errorbar_limits.py b/examples/statistics/errorbar_limits.py index a878f6af3b5c..4044d50cdaf8 100644 --- a/examples/statistics/errorbar_limits.py +++ b/examples/statistics/errorbar_limits.py @@ -58,8 +58,8 @@ # mock up some limits by modifying previous data xlolims = lolims xuplims = uplims -lolims = np.zeros(x.shape) -uplims = np.zeros(x.shape) +lolims = np.zeros_like(x) +uplims = np.zeros_like(x) lolims[[6]] = True # only limited at this index uplims[[3]] = True # only limited at this index diff --git a/examples/subplots_axes_and_figures/axes_box_aspect.py b/examples/subplots_axes_and_figures/axes_box_aspect.py index 862a979fa3e1..9b4954893f63 100644 --- a/examples/subplots_axes_and_figures/axes_box_aspect.py +++ b/examples/subplots_axes_and_figures/axes_box_aspect.py @@ -106,7 +106,7 @@ axs[1, 0].set_box_aspect(1) axs[1, 1].set_box_aspect(3/1) -x, y = np.random.randn(2, 400) * np.array([[.5], [180]]) +x, y = np.random.randn(2, 400) * [[.5], [180]] axs[1, 0].scatter(x, y) axs[0, 0].hist(x) axs[1, 1].hist(y, orientation="horizontal") diff --git a/examples/text_labels_and_annotations/custom_legends.py b/examples/text_labels_and_annotations/custom_legends.py index f37cd2ab61fd..10f680327920 100644 --- a/examples/text_labels_and_annotations/custom_legends.py +++ b/examples/text_labels_and_annotations/custom_legends.py @@ -27,8 +27,8 @@ np.random.seed(19680801) N = 10 -data = [np.logspace(0, 1, 100) + np.random.randn(100) + ii for ii in range(N)] -data = np.array(data).T +data = np.transpose([np.logspace(0, 1, 100) + np.random.randn(100) + ii + for ii in range(N)]) cmap = plt.cm.coolwarm rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, N))) diff --git a/examples/text_labels_and_annotations/text_rotation_relative_to_line.py b/examples/text_labels_and_annotations/text_rotation_relative_to_line.py index 572797b82f0c..23b0522a2956 100644 --- a/examples/text_labels_and_annotations/text_rotation_relative_to_line.py +++ b/examples/text_labels_and_annotations/text_rotation_relative_to_line.py @@ -17,11 +17,13 @@ import matplotlib.pyplot as plt import numpy as np +fig, ax = plt.subplots() + # Plot diagonal line (45 degrees) -h = plt.plot(np.arange(0, 10), np.arange(0, 10)) +h = ax.plot(range(0, 10), range(0, 10)) # set limits so that it no longer looks on screen to be 45 degrees -plt.xlim([-10, 20]) +ax.set_xlim([-10, 20]) # Locations to plot text l1 = np.array((1, 1)) @@ -29,13 +31,12 @@ # Rotate angle angle = 45 -trans_angle = plt.gca().transData.transform_angles(np.array((45,)), - l2.reshape((1, 2)))[0] +trans_angle = ax.transData.transform_angles([45], l2.reshape((1, 2)))[0] # Plot text -th1 = plt.text(l1[0], l1[1], 'text not rotated correctly', fontsize=16, - rotation=angle, rotation_mode='anchor') -th2 = plt.text(l2[0], l2[1], 'text rotated correctly', fontsize=16, - rotation=trans_angle, rotation_mode='anchor') +th1 = ax.text(*l1, 'text not rotated correctly', fontsize=16, + rotation=angle, rotation_mode='anchor') +th2 = ax.text(*l2, 'text rotated correctly', fontsize=16, + rotation=trans_angle, rotation_mode='anchor') plt.show() diff --git a/examples/ticks_and_spines/date_concise_formatter.py b/examples/ticks_and_spines/date_concise_formatter.py index da172c597cf8..aa1721898081 100644 --- a/examples/ticks_and_spines/date_concise_formatter.py +++ b/examples/ticks_and_spines/date_concise_formatter.py @@ -24,8 +24,7 @@ # First, the default formatter. base = datetime.datetime(2005, 2, 1) -dates = np.array([base + datetime.timedelta(hours=(2 * i)) - for i in range(732)]) +dates = [base + datetime.timedelta(hours=(2 * i)) for i in range(732)] N = len(dates) np.random.seed(19680801) y = np.cumsum(np.random.randn(N)) diff --git a/examples/units/ellipse_with_units.py b/examples/units/ellipse_with_units.py index 4377d91d9d58..2a2242cde30c 100644 --- a/examples/units/ellipse_with_units.py +++ b/examples/units/ellipse_with_units.py @@ -30,7 +30,7 @@ ]) -x, y = np.dot(R, np.array([x, y])) +x, y = np.dot(R, [x, y]) x += xcenter y += ycenter pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy