From de302f55d15fc3c83476e2dcd735eac594c37bc3 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 14:23:52 -0800 Subject: [PATCH 1/6] Call min/max directly on generator or two args. --- doc/utils/pylab_names.py | 13 ++++----- examples/axes_grid1/scatter_hist.py | 2 +- examples/pylab_examples/scatter_hist.py | 2 +- examples/widgets/menu.py | 4 +-- lib/matplotlib/artist.py | 7 ++--- lib/matplotlib/axes/_axes.py | 8 +++--- lib/matplotlib/mathtext.py | 4 +-- lib/matplotlib/offsetbox.py | 10 +++---- lib/matplotlib/patches.py | 6 ++-- lib/matplotlib/ticker.py | 8 ++---- lib/matplotlib/tight_layout.py | 22 ++++++--------- lib/matplotlib/transforms.py | 10 +++---- lib/mpl_toolkits/axisartist/axis_artist.py | 32 ++++++++++------------ lib/mpl_toolkits/tests/test_axes_grid1.py | 2 +- 14 files changed, 59 insertions(+), 71 deletions(-) diff --git a/doc/utils/pylab_names.py b/doc/utils/pylab_names.py index 379c6baabca8..164a077bc5e2 100644 --- a/doc/utils/pylab_names.py +++ b/doc/utils/pylab_names.py @@ -46,16 +46,13 @@ print() funcs, docs = zip(*modd[mod]) - maxfunc = max([len(f) for f in funcs]) - maxdoc = max(40, max([len(d) for d in docs]) ) - border = ' '.join(['='*maxfunc, '='*maxdoc]) + maxfunc = max(len(f) for f in funcs) + maxdoc = max(40, max(len(d) for d in docs)) + border = '=' * maxfunc + ' ' + '=' * maxdoc print(border) - print(' '.join(['symbol'.ljust(maxfunc), 'description'.ljust(maxdoc)])) + print('{:<{}} {:<{}}'.format('symbol', maxfunc, 'description', maxdoc)) print(border) for func, doc in modd[mod]: - row = ' '.join([func.ljust(maxfunc), doc.ljust(maxfunc)]) - print(row) - + print('{:<{}} {:<{}}'.format(func, maxfunc, doc, maxdoc)) print(border) print() - #break diff --git a/examples/axes_grid1/scatter_hist.py b/examples/axes_grid1/scatter_hist.py index 52e0fc6680d4..97a0893b5ee2 100644 --- a/examples/axes_grid1/scatter_hist.py +++ b/examples/axes_grid1/scatter_hist.py @@ -30,7 +30,7 @@ # now determine nice limits by hand: binwidth = 0.25 -xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))]) +xymax = max(np.max(np.abs(x)), np.max(np.abs(y))) lim = (int(xymax/binwidth) + 1)*binwidth bins = np.arange(-lim, lim + binwidth, binwidth) diff --git a/examples/pylab_examples/scatter_hist.py b/examples/pylab_examples/scatter_hist.py index 420c79359a21..adbc08c199db 100644 --- a/examples/pylab_examples/scatter_hist.py +++ b/examples/pylab_examples/scatter_hist.py @@ -37,7 +37,7 @@ # now determine nice limits by hand: binwidth = 0.25 -xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))]) +xymax = max(np.max(np.abs(x)), np.max(np.abs(y))) lim = (int(xymax/binwidth) + 1) * binwidth axScatter.set_xlim((-lim, lim)) diff --git a/examples/widgets/menu.py b/examples/widgets/menu.py index 846dd5ce1917..e4662d0e6644 100644 --- a/examples/widgets/menu.py +++ b/examples/widgets/menu.py @@ -126,8 +126,8 @@ def __init__(self, fig, menuitems): self.menuitems = menuitems self.numitems = len(menuitems) - maxw = max([item.labelwidth for item in menuitems]) - maxh = max([item.labelheight for item in menuitems]) + maxw = max(item.labelwidth for item in menuitems) + maxh = max(item.labelheight for item in menuitems) totalh = self.numitems*maxh + (self.numitems + 1)*2*MenuItem.pady diff --git a/lib/matplotlib/artist.py b/lib/matplotlib/artist.py index 4c9e59d7deea..2face4558c05 100644 --- a/lib/matplotlib/artist.py +++ b/lib/matplotlib/artist.py @@ -1278,12 +1278,11 @@ def pprint_setters_rest(self, prop=None, leadingspace=2): ######## names = [self.aliased_name_rest(prop, target) - for prop, target - in attrs] + for prop, target in attrs] accepts = [self.get_valid_values(prop) for prop, target in attrs] - col0_len = max([len(n) for n in names]) - col1_len = max([len(a) for a in accepts]) + col0_len = max(len(n) for n in names) + col1_len = max(len(a) for a in accepts) table_formatstr = pad + '=' * col0_len + ' ' + '=' * col1_len lines.append('') diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index 2bf1bcc3e048..ee755b377c08 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2162,17 +2162,17 @@ def make_iterable(x): if adjust_xlim: xmin, xmax = self.dataLim.intervalx - xmin = np.amin([w for w in width if w > 0]) + xmin = np.min(w for w in width if w > 0) if xerr is not None: - xmin = xmin - np.amax(xerr) + xmin = xmin - np.max(xerr) xmin = max(xmin * 0.9, 1e-100) self.dataLim.intervalx = (xmin, xmax) if adjust_ylim: ymin, ymax = self.dataLim.intervaly - ymin = np.amin([h for h in height if h > 0]) + ymin = np.min(h for h in height if h > 0) if yerr is not None: - ymin = ymin - np.amax(yerr) + ymin = ymin - np.max(yerr) ymin = max(ymin * 0.9, 1e-100) self.dataLim.intervaly = (ymin, ymax) self.autoscale_view() diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index 187b2a3c525b..5db875afeae3 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -3183,8 +3183,8 @@ def overline(self, s, loc, toks): def _auto_sized_delimiter(self, front, middle, back): state = self.get_state() if len(middle): - height = max([x.height for x in middle]) - depth = max([x.depth for x in middle]) + height = max(x.height for x in middle) + depth = max(x.depth for x in middle) factor = None else: height = 0 diff --git a/lib/matplotlib/offsetbox.py b/lib/matplotlib/offsetbox.py index de2760409a1b..9e5b2593d88b 100644 --- a/lib/matplotlib/offsetbox.py +++ b/lib/matplotlib/offsetbox.py @@ -119,11 +119,11 @@ def _get_aligned_offsets(hd_list, height, align="baseline"): """ if height is None: - height = max([h for h, d in hd_list]) + height = max(h for h, d in hd_list) if align == "baseline": - height_descent = max([h - d for h, d in hd_list]) - descent = max([d for h, d in hd_list]) + height_descent = max(h - d for h, d in hd_list) + descent = max(d for h, d in hd_list) height = height_descent + descent offsets = [0. for h, d in hd_list] elif align in ["left", "top"]: @@ -465,8 +465,8 @@ def get_extent_offsets(self, renderer): return 2 * pad, 2 * pad, pad, pad, [] if self.height is None: - height_descent = max([h - yd for w, h, xd, yd in whd_list]) - ydescent = max([yd for w, h, xd, yd in whd_list]) + height_descent = max(h - yd for w, h, xd, yd in whd_list) + ydescent = max(yd for w, h, xd, yd in whd_list) height = height_descent + ydescent else: height = self.height - 2 * pad # width w/o pad diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index fd4b745e1f2d..8edc5976ead4 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1773,7 +1773,7 @@ def _pprint_table(_table, leadingspace=2): for column, cell in zip(columns, row): column.append(cell) - col_len = [max([len(cell) for cell in column]) for column in columns] + col_len = [max(len(cell) for cell in column) for column in columns] lines = [] table_formatstr = pad + ' '.join([('=' * cl) for cl in col_len]) @@ -2050,8 +2050,8 @@ def transmute(self, x0, y0, width, height, mutation_size): # boundary of the padded box x0, y0 = x0 - pad, y0 - pad, - return Path.circle((x0 + width/2., y0 + height/2.), - (max([width, height]) / 2.)) + return Path.circle((x0 + width / 2, y0 + height / 2), + max(width, height) / 2) _style_list["circle"] = Circle diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index e3fe0d02513b..a0a835b662d6 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -1623,11 +1623,9 @@ def view_limits(self, vmin, vmax): vmax += 1 if rcParams['axes.autolimit_mode'] == 'round_numbers': - exponent, remainder = _divmod(math.log10(vmax - vmin), - math.log10(max([self.numticks-1, 1]))) - if remainder < 0.5: - exponent -= 1 - scale = max([self.numticks-1, 1]) ** (-exponent) + exponent = round(math.log10(vmax - vmin) + / math.log10(max(self.numticks - 1, 1))) - 1 + scale = max(self.numticks - 1, 1) ** (-exponent) vmin = math.floor(scale * vmin) / scale vmax = math.ceil(scale * vmax) / scale diff --git a/lib/matplotlib/tight_layout.py b/lib/matplotlib/tight_layout.py index 18a19370a092..1f61d95e9f2f 100644 --- a/lib/matplotlib/tight_layout.py +++ b/lib/matplotlib/tight_layout.py @@ -188,22 +188,18 @@ def auto_adjust_subplotpars(fig, renderer, top=1 - margin_top) if cols > 1: - hspace = max([sum(s) - for i in range(rows) - for s - in hspaces[i * (cols + 1) + 1:(i + 1) * (cols + 1) - 1]]) - hspace += hpad_inches / fig_width_inch - h_axes = ((1 - margin_right - margin_left) - - hspace * (cols - 1)) / cols - + hspace = ( + max(sum(s) + for i in range(rows) + for s in hspaces[i * (cols + 1) + 1:(i + 1) * (cols + 1) - 1]) + + hpad_inches / fig_width_inch) + h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols kwargs["wspace"] = hspace / h_axes if rows > 1: - vspace = max([sum(s) for s in vspaces[cols:-cols]]) - vspace += vpad_inches / fig_height_inch - v_axes = ((1 - margin_top - margin_bottom) - - vspace * (rows - 1)) / rows - + vspace = (max(sum(s) for s in vspaces[cols:-cols]) + + vpad_inches / fig_height_inch) + v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows kwargs["hspace"] = vspace / v_axes return kwargs diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index fca485d2a182..568243da8ad7 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -761,10 +761,10 @@ def intersection(bbox1, bbox2): bbox2.ymax < bbox1.ymin) if intersects: - x0 = max([bbox1.xmin, bbox2.xmin]) - x1 = min([bbox1.xmax, bbox2.xmax]) - y0 = max([bbox1.ymin, bbox2.ymin]) - y1 = min([bbox1.ymax, bbox2.ymax]) + x0 = max(bbox1.xmin, bbox2.xmin) + x1 = min(bbox1.xmax, bbox2.xmax) + y0 = max(bbox1.ymin, bbox2.ymin) + y1 = min(bbox1.ymax, bbox2.ymax) return Bbox.from_extents(x0, y0, x1, y1) return None @@ -2115,7 +2115,7 @@ def contains_branch_seperately(self, transform): @property def depth(self): - return max([self._x.depth, self._y.depth]) + return max(self._x.depth, self._y.depth) def contains_branch(self, other): # a blended transform cannot possibly contain a branch from two different transforms. diff --git a/lib/mpl_toolkits/axisartist/axis_artist.py b/lib/mpl_toolkits/axisartist/axis_artist.py index a8c7c7f87f7b..1f2754ff12ed 100644 --- a/lib/mpl_toolkits/axisartist/axis_artist.py +++ b/lib/mpl_toolkits/axisartist/axis_artist.py @@ -714,37 +714,37 @@ def _get_ticklabels_offsets(self, renderer, label_direction): va, ha = self.get_va(), self.get_ha() if label_direction == "left": - pad = max([w for (w, h, d) in whd_list]) + pad = max(w for w, h, d in whd_list) if ha == "left": r = pad elif ha == "center": r = .5 * pad elif label_direction == "right": - pad = max([w for (w, h, d) in whd_list]) + pad = max(w for w, h, d in whd_list) if ha == "right": r = pad elif ha == "center": r = .5 * pad elif label_direction == "bottom": - pad = max([h for (w, h, d) in whd_list]) + pad = max(h for w, h, d in whd_list) if va == "bottom": r = pad elif va == "center": r =.5 * pad elif va == "baseline": - max_ascent = max([(h-d) for (w, h, d) in whd_list]) - max_descent = max([d for (w, h, d) in whd_list]) + max_ascent = max(h - d for w, h, d in whd_list) + max_descent = max(d for w, h, d in whd_list) r = max_ascent pad = max_ascent + max_descent elif label_direction == "top": - pad = max([h for (w, h, d) in whd_list]) + pad = max(h for w, h, d in whd_list) if va == "top": r = pad elif va == "center": r =.5 * pad elif va == "baseline": - max_ascent = max([(h-d) for (w, h, d) in whd_list]) - max_descent = max([d for (w, h, d) in whd_list]) + max_ascent = max(h - d for w, h, d in whd_list) + max_descent = max(d for w, h, d in whd_list) r = max_descent pad = max_ascent + max_descent @@ -1432,7 +1432,7 @@ def _update_label(self, renderer): #print self._ticklabel_add_angle - self._axislabel_add_angle #if abs(self._ticklabel_add_angle - self._axislabel_add_angle)%360 > 90: - if self._ticklabel_add_angle != self._axislabel_add_angle: + if self._ticklabel_add_angle != self._axislabel_add_angle: if (self.major_ticks.get_visible() and not self.major_ticks.get_tick_out()) \ or \ (self.minor_ticks.get_visible() and not self.major_ticks.get_tick_out()): @@ -1440,8 +1440,8 @@ def _update_label(self, renderer): else: axislabel_pad = 0 else: - axislabel_pad = max([self.major_ticklabels._axislabel_pad, - self.minor_ticklabels._axislabel_pad]) + axislabel_pad = max(self.major_ticklabels._axislabel_pad, + self.minor_ticklabels._axislabel_pad) #label_offset = axislabel_pad + self.LABELPAD @@ -1477,7 +1477,7 @@ def _draw_label2(self, renderer): #print self._ticklabel_add_angle - self._axislabel_add_angle #if abs(self._ticklabel_add_angle - self._axislabel_add_angle)%360 > 90: - if self._ticklabel_add_angle != self._axislabel_add_angle: + if self._ticklabel_add_angle != self._axislabel_add_angle: if (self.major_ticks.get_visible() and not self.major_ticks.get_tick_out()) \ or \ (self.minor_ticks.get_visible() and not self.major_ticks.get_tick_out()): @@ -1485,9 +1485,8 @@ def _draw_label2(self, renderer): else: axislabel_pad = 0 else: - axislabel_pad = max([self.major_ticklabels._axislabel_pad, - self.minor_ticklabels._axislabel_pad]) - + axislabel_pad = max(self.major_ticklabels._axislabel_pad, + self.minor_ticklabels._axislabel_pad) #label_offset = axislabel_pad + self.LABELPAD @@ -1497,8 +1496,7 @@ def _draw_label2(self, renderer): xy, angle_tangent = self._axis_artist_helper.get_axislabel_pos_angle(self.axes) if xy is None: return - angle_label = angle_tangent - 90 - + angle_label = angle_tangent - 90 x, y = xy self.label._set_ref_angle(angle_label+self._axislabel_add_angle) diff --git a/lib/mpl_toolkits/tests/test_axes_grid1.py b/lib/mpl_toolkits/tests/test_axes_grid1.py index b0d2f742b580..a81f7e01c7d2 100644 --- a/lib/mpl_toolkits/tests/test_axes_grid1.py +++ b/lib/mpl_toolkits/tests/test_axes_grid1.py @@ -43,7 +43,7 @@ def test_divider_append_axes(): # now determine nice limits by hand: binwidth = 0.25 - xymax = np.max([np.max(np.fabs(x)), np.max(np.fabs(y))]) + xymax = max(np.max(np.abs(x)), np.max(np.abs(y))) lim = (int(xymax/binwidth) + 1) * binwidth bins = np.arange(-lim, lim + binwidth, binwidth) From 46b9d473e392edc991ff1252c76ef49d92cbaa82 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Tue, 28 Jun 2016 11:58:20 -0700 Subject: [PATCH 2/6] Remove old `__cmp__` method. --- lib/matplotlib/transforms.py | 7 ------- 1 file changed, 7 deletions(-) diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index 568243da8ad7..98404ec66f9b 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -1826,13 +1826,6 @@ def __init__(self, matrix=None, **kwargs): def __repr__(self): return "Affine2D(%s)" % repr(self._mtx) -# def __cmp__(self, other): -# # XXX redundant. this only tells us eq. -# if (isinstance(other, Affine2D) and -# (self.get_matrix() == other.get_matrix()).all()): -# return 0 -# return -1 - @staticmethod def from_values(a, b, c, d, e, f): """ From 1504540735618284108f7a6265e875e7e3abaa42 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Wed, 30 Nov 2016 22:40:12 -0800 Subject: [PATCH 3/6] Use reshape instead of assigning to shape. --- examples/axes_grid1/simple_axesgrid.py | 3 +- examples/pylab_examples/agg_buffer.py | 3 +- examples/pylab_examples/barcode_demo.py | 7 +-- examples/pylab_examples/figimage_demo.py | 9 ++-- examples/pylab_examples/image_demo2.py | 5 +-- examples/pylab_examples/image_origin.py | 3 +- examples/pylab_examples/layer_images.py | 3 +- examples/pylab_examples/mri_demo.py | 3 +- examples/pylab_examples/mri_with_eeg.py | 3 +- .../histogram_demo_canvasagg.py | 3 +- lib/matplotlib/axes/_axes.py | 36 +++++---------- lib/matplotlib/backends/backend_gdk.py | 44 +++++-------------- .../backends/backend_webagg_core.py | 11 +++-- lib/matplotlib/collections.py | 19 +++----- lib/matplotlib/colors.py | 16 +++---- lib/matplotlib/mlab.py | 4 +- lib/matplotlib/quiver.py | 7 +-- lib/matplotlib/tests/test_axes.py | 13 ++---- lib/matplotlib/tests/test_cbook.py | 6 +-- lib/matplotlib/tri/trifinder.py | 4 +- 20 files changed, 63 insertions(+), 139 deletions(-) diff --git a/examples/axes_grid1/simple_axesgrid.py b/examples/axes_grid1/simple_axesgrid.py index b8c45f2aae6d..2b6b82bd538c 100644 --- a/examples/axes_grid1/simple_axesgrid.py +++ b/examples/axes_grid1/simple_axesgrid.py @@ -2,8 +2,7 @@ from mpl_toolkits.axes_grid1 import ImageGrid import numpy as np -im = np.arange(100) -im.shape = 10, 10 +im = np.arange(100).reshape((10, 10)) fig = plt.figure(1, (4., 4.)) grid = ImageGrid(fig, 111, # similar to subplot(111) diff --git a/examples/pylab_examples/agg_buffer.py b/examples/pylab_examples/agg_buffer.py index cf7042793ba0..9c41e3c562d3 100755 --- a/examples/pylab_examples/agg_buffer.py +++ b/examples/pylab_examples/agg_buffer.py @@ -26,8 +26,7 @@ l, b, w, h = agg.figure.bbox.bounds w, h = int(w), int(h) -X = np.fromstring(s, np.uint8) -X.shape = h, w, 3 +X = np.fromstring(s, np.uint8).reshape((h, w, 3)) try: im = Image.fromstring("RGB", (w, h), s) diff --git a/examples/pylab_examples/barcode_demo.py b/examples/pylab_examples/barcode_demo.py index 03a39f2b3dd2..ef7ba7d7fa76 100644 --- a/examples/pylab_examples/barcode_demo.py +++ b/examples/pylab_examples/barcode_demo.py @@ -14,15 +14,12 @@ fig = plt.figure() # a vertical barcode -- this is broken at present -x.shape = len(x), 1 ax = fig.add_axes([0.1, 0.3, 0.1, 0.6], **axprops) -ax.imshow(x, **barprops) +ax.imshow(x.reshape((-1, 1)), **barprops) -x = x.copy() # a horizontal barcode -x.shape = 1, len(x) ax = fig.add_axes([0.3, 0.1, 0.6, 0.1], **axprops) -ax.imshow(x, **barprops) +ax.imshow(x.reshape((1, -1)), **barprops) plt.show() diff --git a/examples/pylab_examples/figimage_demo.py b/examples/pylab_examples/figimage_demo.py index 56c78d3bdbf1..d14d5ec282a0 100644 --- a/examples/pylab_examples/figimage_demo.py +++ b/examples/pylab_examples/figimage_demo.py @@ -9,11 +9,10 @@ fig = plt.figure() -Z = np.arange(10000.0) -Z.shape = 100, 100 -Z[:, 50:] = 1. +Z = np.arange(10000).reshape(100, 100) +Z[:, 50:] = 1 -im1 = plt.figimage(Z, xo=50, yo=0, origin='lower') -im2 = plt.figimage(Z, xo=100, yo=100, alpha=.8, origin='lower') +im1 = fig.figimage(Z, xo=50, yo=0, origin='lower') +im2 = fig.figimage(Z, xo=100, yo=100, alpha=.8, origin='lower') plt.show() diff --git a/examples/pylab_examples/image_demo2.py b/examples/pylab_examples/image_demo2.py index 998e383d2181..7c6c1a64494d 100755 --- a/examples/pylab_examples/image_demo2.py +++ b/examples/pylab_examples/image_demo2.py @@ -7,9 +7,8 @@ datafile = cbook.get_sample_data('ct.raw.gz', asfileobj=True) s = datafile.read() -A = np.fromstring(s, np.uint16).astype(float) -A *= 1.0 / max(A) -A.shape = w, h +A = np.fromstring(s, np.uint16).astype(float).reshape((w, h)) +A /= A.max() extent = (0, 25, 0, 25) im = plt.imshow(A, cmap=plt.cm.hot, origin='upper', extent=extent) diff --git a/examples/pylab_examples/image_origin.py b/examples/pylab_examples/image_origin.py index 0e282dd7fb65..b337291237b3 100755 --- a/examples/pylab_examples/image_origin.py +++ b/examples/pylab_examples/image_origin.py @@ -7,8 +7,7 @@ import matplotlib.pyplot as plt import numpy as np -x = np.arange(120) -x.shape = (10, 12) +x = np.arange(120).reshape((10, 12)) interp = 'bilinear' fig, axs = plt.subplots(nrows=2, sharex=True, figsize=(3, 5)) diff --git a/examples/pylab_examples/layer_images.py b/examples/pylab_examples/layer_images.py index 1a8675c2bb06..bd8119b5fa8d 100644 --- a/examples/pylab_examples/layer_images.py +++ b/examples/pylab_examples/layer_images.py @@ -28,8 +28,7 @@ def func3(x, y): extent = xmin, xmax, ymin, ymax fig = plt.figure(frameon=False) -Z1 = np.array(([0, 1]*4 + [1, 0]*4)*4) -Z1.shape = (8, 8) # chessboard +Z1 = np.add.outer(range(8), range(8)) % 2 # chessboard im1 = plt.imshow(Z1, cmap=plt.cm.gray, interpolation='nearest', extent=extent) diff --git a/examples/pylab_examples/mri_demo.py b/examples/pylab_examples/mri_demo.py index 6574b0bf7e17..0840e5222f46 100755 --- a/examples/pylab_examples/mri_demo.py +++ b/examples/pylab_examples/mri_demo.py @@ -9,8 +9,7 @@ # Data are 256x256 16 bit integers dfile = cbook.get_sample_data('s1045.ima.gz') -im = np.fromstring(dfile.read(), np.uint16).astype(float) -im.shape = (256, 256) +im = np.fromstring(dfile.read(), np.uint16).reshape((256, 256)) dfile.close() ax.imshow(im, cmap=cm.gray) diff --git a/examples/pylab_examples/mri_with_eeg.py b/examples/pylab_examples/mri_with_eeg.py index 2a601ea707a2..433feb0b2c3c 100755 --- a/examples/pylab_examples/mri_with_eeg.py +++ b/examples/pylab_examples/mri_with_eeg.py @@ -16,8 +16,7 @@ # Load the MRI data (256x256 16 bit integers) dfile = cbook.get_sample_data('s1045.ima.gz') -im = np.fromstring(dfile.read(), np.uint16).astype(float) -im.shape = (256, 256) +im = np.fromstring(dfile.read(), np.uint16).astype(float).reshape((256, 256)) dfile.close() # Plot the MRI image diff --git a/examples/user_interfaces/histogram_demo_canvasagg.py b/examples/user_interfaces/histogram_demo_canvasagg.py index 11a13ba12185..27b45c0d232e 100644 --- a/examples/user_interfaces/histogram_demo_canvasagg.py +++ b/examples/user_interfaces/histogram_demo_canvasagg.py @@ -48,8 +48,7 @@ if 0: # convert to a numpy array - X = numpy.fromstring(s, numpy.uint8) - X.shape = h, w, 3 + X = numpy.fromstring(s, numpy.uint8).reshape((h, w, 3)) if 0: # pass off to PIL diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index ee755b377c08..cb2797134f00 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -4264,35 +4264,23 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, d2 = (x - ix2 - 0.5) ** 2 + 3.0 * (y - iy2 - 0.5) ** 2 bdist = (d1 < d2) if C is None: - accum = np.zeros(n) - # Create appropriate views into "accum" array. - lattice1 = accum[:nx1 * ny1] - lattice2 = accum[nx1 * ny1:] - lattice1.shape = (nx1, ny1) - lattice2.shape = (nx2, ny2) + lattice1 = np.zeros((nx1, ny1)) + lattice2 = np.zeros((nx2, ny2)) for i in xrange(len(x)): if bdist[i]: - if ((ix1[i] >= 0) and (ix1[i] < nx1) and - (iy1[i] >= 0) and (iy1[i] < ny1)): + if 0 <= ix1[i] < nx1 and 0 <= iy1[i] < ny1: lattice1[ix1[i], iy1[i]] += 1 else: - if ((ix2[i] >= 0) and (ix2[i] < nx2) and - (iy2[i] >= 0) and (iy2[i] < ny2)): + if 0 <= ix2[i] < nx2 and 0 <= iy2[i] < ny2: lattice2[ix2[i], iy2[i]] += 1 # threshold if mincnt is not None: - for i in xrange(nx1): - for j in xrange(ny1): - if lattice1[i, j] < mincnt: - lattice1[i, j] = np.nan - for i in xrange(nx2): - for j in xrange(ny2): - if lattice2[i, j] < mincnt: - lattice2[i, j] = np.nan - accum = np.hstack((lattice1.astype(float).ravel(), - lattice2.astype(float).ravel())) + lattice1[lattice1 < mincnt] = np.nan + lattice2[lattice2 < mincnt] = np.nan + accum = np.hstack((lattice1.ravel(), + lattice2.ravel())) good_idxs = ~np.isnan(accum) else: @@ -4311,12 +4299,10 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, for i in xrange(len(x)): if bdist[i]: - if ((ix1[i] >= 0) and (ix1[i] < nx1) and - (iy1[i] >= 0) and (iy1[i] < ny1)): + if 0 <= ix1[i] < nx1 and 0 <= iy1[i] < ny1: lattice1[ix1[i], iy1[i]].append(C[i]) else: - if ((ix2[i] >= 0) and (ix2[i] < nx2) and - (iy2[i] >= 0) and (iy2[i] < ny2)): + if 0 <= ix2[i] < nx2 and 0 <= iy2[i] < ny2: lattice2[ix2[i], iy2[i]].append(C[i]) for i in xrange(nx1): @@ -6612,7 +6598,6 @@ def psd(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, pxx, freqs = mlab.psd(x=x, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq) - pxx.shape = len(freqs), freqs += Fc if scale_by_freq in (None, True): @@ -6736,7 +6721,6 @@ def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None, pxy, freqs = mlab.csd(x=x, y=y, NFFT=NFFT, Fs=Fs, detrend=detrend, window=window, noverlap=noverlap, pad_to=pad_to, sides=sides, scale_by_freq=scale_by_freq) - pxy.shape = len(freqs), # pxy is complex freqs += Fc diff --git a/lib/matplotlib/backends/backend_gdk.py b/lib/matplotlib/backends/backend_gdk.py index 13fba478afe5..d750a09f01a0 100644 --- a/lib/matplotlib/backends/backend_gdk.py +++ b/lib/matplotlib/backends/backend_gdk.py @@ -134,7 +134,6 @@ def draw_image(self, gc, x, y, im): int(x), int(y), cols, rows, gdk.RGB_DITHER_NONE, 0, 0) - def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): x, y = int(x), int(y) @@ -158,31 +157,17 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): self.gdkDrawable.draw_layout(gc.gdkGC, x, y-h-b, layout) - def _draw_mathtext(self, gc, x, y, s, prop, angle): ox, oy, width, height, descent, font_image, used_characters = \ self.mathtext_parser.parse(s, self.dpi, prop) - if angle==90: + if angle == 90: width, height = height, width x -= width y -= height imw = font_image.get_width() imh = font_image.get_height() - N = imw * imh - - # a numpixels by num fonts array - Xall = np.zeros((N,1), np.uint8) - - image_str = font_image.as_str() - Xall[:,0] = np.fromstring(image_str, np.uint8) - - # get the max alpha at each pixel - Xs = np.amax(Xall,axis=1) - - # convert it to it's proper shape - Xs.shape = imh, imw pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, has_alpha=True, bits_per_sample=8, width=imw, height=imh) @@ -190,22 +175,16 @@ def _draw_mathtext(self, gc, x, y, s, prop, angle): array = pixbuf_get_pixels_array(pixbuf) rgb = gc.get_rgb() - array[:,:,0]=int(rgb[0]*255) - array[:,:,1]=int(rgb[1]*255) - array[:,:,2]=int(rgb[2]*255) - array[:,:,3]=Xs - - try: # new in 2.2 - # can use None instead of gc.gdkGC, if don't need clipping - self.gdkDrawable.draw_pixbuf (gc.gdkGC, pixbuf, 0, 0, - int(x), int(y), imw, imh, - gdk.RGB_DITHER_NONE, 0, 0) - except AttributeError: - # deprecated in 2.2 - pixbuf.render_to_drawable(self.gdkDrawable, gc.gdkGC, 0, 0, - int(x), int(y), imw, imh, - gdk.RGB_DITHER_NONE, 0, 0) + array[:,:,0] = int(rgb[0]*255) + array[:,:,1] = int(rgb[1]*255) + array[:,:,2] = int(rgb[2]*255) + array[:,:,3] = ( + np.fromstring(font_image.as_str(), np.uint8).reshape((imh, imw))) + # can use None instead of gc.gdkGC, if don't need clipping + self.gdkDrawable.draw_pixbuf(gc.gdkGC, pixbuf, 0, 0, + int(x), int(y), imw, imh, + gdk.RGB_DITHER_NONE, 0, 0) def _draw_rotated_text(self, gc, x, y, s, prop, angle): """ @@ -259,7 +238,6 @@ def _draw_rotated_text(self, gc, x, y, s, prop, angle): gdrawable.draw_image(ggc, imageVert, 0, 0, x, y, h, w) self.rotated[key] = imageVert - def _get_pango_layout(self, s, prop): """ Create a pango layout instance for Text 's' with properties 'prop'. @@ -293,7 +271,6 @@ def _get_pango_layout(self, s, prop): self.layoutd[key] = layout, inkRect, logicalRect return layout, inkRect, logicalRect - def flipy(self): return True @@ -315,7 +292,6 @@ def get_text_width_height_descent(self, s, prop, ismath): def new_gc(self): return GraphicsContextGDK(renderer=self) - def points_to_pixels(self, points): return points/72.0 * self.dpi diff --git a/lib/matplotlib/backends/backend_webagg_core.py b/lib/matplotlib/backends/backend_webagg_core.py index d13b901ac71b..37ce69c59103 100644 --- a/lib/matplotlib/backends/backend_webagg_core.py +++ b/lib/matplotlib/backends/backend_webagg_core.py @@ -207,8 +207,8 @@ def get_diff_image(self): # The buffer is created as type uint32 so that entire # pixels can be compared in one numpy call, rather than # needing to compare each plane separately. - buff = np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) - buff.shape = (renderer.height, renderer.width) + buff = (np.frombuffer(renderer.buffer_rgba(), dtype=np.uint32) + .reshape((renderer.height, renderer.width))) # If any pixels have transparency, we need to force a full # draw as we cannot overlay new on top of old. @@ -219,10 +219,9 @@ def get_diff_image(self): output = buff else: self.set_image_mode('diff') - last_buffer = np.frombuffer(self._last_renderer.buffer_rgba(), - dtype=np.uint32) - last_buffer.shape = (renderer.height, renderer.width) - + last_buffer = (np.frombuffer(self._last_renderer.buffer_rgba(), + dtype=np.uint32) + .reshape((renderer.height, renderer.width))) diff = buff != last_buffer output = np.where(diff, buff, 0) diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index 4af6c550dc82..57700a911cdb 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -83,9 +83,7 @@ class Collection(artist.Artist, cm.ScalarMappable): (i.e., a call to set_array has been made), at draw time a call to scalar mappable will be made to set the face colors. """ - _offsets = np.array([], float) - # _offsets must be a Nx2 array! - _offsets.shape = (0, 2) + _offsets = np.zeros((0, 2)) _transOffset = transforms.IdentityTransform() #: Either a list of 3x3 arrays or an Nx3x3 array of transforms, suitable #: for the `all_transforms` argument to @@ -147,8 +145,7 @@ def __init__(self, self._uniform_offsets = None self._offsets = np.array([[0, 0]], float) if offsets is not None: - offsets = np.asanyarray(offsets) - offsets.shape = (-1, 2) # Make it Nx2 + offsets = np.asanyarray(offsets).reshape((-1, 2)) if transOffset is not None: self._offsets = offsets self._transOffset = transOffset @@ -213,11 +210,10 @@ def get_datalim(self, transData): offsets = transOffset.transform_non_affine(offsets) transOffset = transOffset.get_affine() - offsets = np.asanyarray(offsets, float) + offsets = np.asanyarray(offsets, float).reshape((-1, 2)) if isinstance(offsets, np.ma.MaskedArray): offsets = offsets.filled(np.nan) # get_path_collection_extents handles nan but not masked arrays - offsets.shape = (-1, 2) # Make it Nx2 if len(paths) and len(offsets): result = mpath.get_path_collection_extents( @@ -255,8 +251,7 @@ def _prepare_points(self): ys = self.convert_yunits(offsets[:, 1]) offsets = list(zip(xs, ys)) - offsets = np.asanyarray(offsets, float) - offsets.shape = (-1, 2) # Make it Nx2 + offsets = np.asanyarray(offsets, float).reshape((-1, 2)) if not transform.is_affine: paths = [transform.transform_path_non_affine(path) @@ -436,8 +431,7 @@ def set_offsets(self, offsets): ACCEPTS: float or sequence of floats """ - offsets = np.asanyarray(offsets, float) - offsets.shape = (-1, 2) # Make it Nx2 + offsets = np.asanyarray(offsets, float).reshape((-1, 2)) #This decision is based on how they are initialized above if self._uniform_offsets is None: self._offsets = offsets @@ -1889,8 +1883,7 @@ def draw(self, renderer): ys = self.convert_yunits(self._offsets[:, 1]) offsets = list(zip(xs, ys)) - offsets = np.asarray(offsets, float) - offsets.shape = (-1, 2) # Make it Nx2 + offsets = np.asarray(offsets, float).reshape((-1, 2)) self.update_scalarmappable() diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index e18962ae1be6..b67d9834bc1f 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -1330,15 +1330,14 @@ def rgb_to_hsv(arr): # check length of the last dimension, should be _some_ sort of rgb if arr.shape[-1] != 3: raise ValueError("Last dimension of input array must be 3; " - "shape {shp} was found.".format(shp=arr.shape)) + "shape {} was found.".format(arr.shape)) in_ndim = arr.ndim if arr.ndim == 1: arr = np.array(arr, ndmin=2) # make sure we don't have an int image - if arr.dtype.kind in ('iu'): - arr = arr.astype(np.float32) + arr = arr.astype(np.promote_types(arr.dtype, np.float32)) out = np.zeros_like(arr) arr_max = arr.max(-1) @@ -1396,8 +1395,7 @@ def hsv_to_rgb(hsv): hsv = np.array(hsv, ndmin=2) # make sure we don't have an int image - if hsv.dtype.kind in ('iu'): - hsv = hsv.astype(np.float32) + hsv = hsv.astype(np.promote_types(hsv.dtype, np.float32)) h = hsv[..., 0] s = hsv[..., 1] @@ -1448,13 +1446,11 @@ def hsv_to_rgb(hsv): g[idx] = v[idx] b[idx] = v[idx] - rgb = np.empty_like(hsv) - rgb[..., 0] = r - rgb[..., 1] = g - rgb[..., 2] = b + # `np.stack([r, g, b], axis=-1)` (numpy 1.10). + rgb = np.concatenate([r[..., None], g[..., None], b[..., None]], -1) if in_ndim == 1: - rgb.shape = (3, ) + rgb.shape = (3,) return rgb diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 04c51c4323fe..4390e54bf561 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -1339,9 +1339,7 @@ def cohere(x, y, NFFT=256, Fs=2, detrend=detrend_none, window=window_hanning, scale_by_freq) Pxy, f = csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) - - Cxy = np.divide(np.absolute(Pxy)**2, Pxx*Pyy) - Cxy.shape = (len(f),) + Cxy = np.abs(Pxy) ** 2 / (Pxx * Pxy) return Cxy, f diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py index d5c00cd53f31..557966d5da6f 100644 --- a/lib/matplotlib/quiver.py +++ b/lib/matplotlib/quiver.py @@ -656,11 +656,8 @@ def _make_verts(self, U, V): elif str_angles and (self.angles == 'uv'): theta = np.angle(uv) else: - # Make a copy to avoid changing the input array. - theta = ma.masked_invalid(self.angles, copy=True).filled(0) - theta = theta.ravel() - theta *= (np.pi / 180.0) - theta.shape = (theta.shape[0], 1) # for broadcasting + theta = ma.masked_invalid(np.deg2rad(self.angles)).filled(0) + theta = theta.reshape((-1, 1)) # for broadcasting xy = (X + Y * 1j) * np.exp(1j * theta) * self.width xy = xy[:, :, np.newaxis] XY = np.concatenate((xy.real, xy.imag), axis=2) diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 005a88f91f4f..5c426ee3d2d2 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -386,11 +386,8 @@ def test_shaped_data(): [0.01383268, 0.34060930, 0.76084285, 0.70800694, 0.87634056, 0.08213693, 0.54655021, 0.98123181, 0.44080053, 0.86815815]]) - y1 = np.arange(10) - y1.shape = 1, 10 - - y2 = np.arange(10) - y2.shape = 10, 1 + y1 = np.arange(10).reshape((1, -1)) + y2 = np.arange(10).reshape((-1, 1)) fig = plt.figure() plt.subplot(411) @@ -551,8 +548,7 @@ def test_hexbin_extent(): fig = plt.figure() ax = fig.add_subplot(111) - data = np.arange(2000.)/2000. - data.shape = 2, 1000 + data = (np.arange(2000) / 2000).reshape((2, 1000)) x, y = data ax.hexbin(x, y, extent=[.1, .3, .6, .7]) @@ -583,8 +579,7 @@ def __init__(self, x, y): fig = plt.figure() ax = fig.add_subplot(111) - data = np.arange(200.)/200. - data.shape = 2, 100 + data = (np.arange(200) / 200).reshape((2, 100)) x, y = data hb = ax.hexbin(x, y, extent=[.1, .3, .6, .7], picker=-1) diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index 65136c77bbc6..ca31592ede20 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -21,10 +21,8 @@ def test_is_string_like(): y = np.arange(10) assert not cbook.is_string_like(y) - y.shape = 10, 1 - assert not cbook.is_string_like(y) - y.shape = 1, 10 - assert not cbook.is_string_like(y) + assert not cbook.is_string_like(y.reshape((-1, 1))) + assert not cbook.is_string_like(y.reshape((1, -1))) assert cbook.is_string_like("hello world") assert not cbook.is_string_like(10) diff --git a/lib/matplotlib/tri/trifinder.py b/lib/matplotlib/tri/trifinder.py index 247d061ea1d0..08a07f854f7a 100644 --- a/lib/matplotlib/tri/trifinder.py +++ b/lib/matplotlib/tri/trifinder.py @@ -61,8 +61,8 @@ def __call__(self, x, y): raise ValueError("x and y must be array-like with the same shape") # C++ does the heavy lifting, and expects 1D arrays. - indices = self._cpp_trifinder.find_many(x.ravel(), y.ravel()) - indices.shape = x.shape + indices = (self._cpp_trifinder.find_many(x.ravel(), y.ravel()) + .reshape(x.shape)) return indices def _get_tree_stats(self): From 3d00576eced6fa68eb34136e457510c00521baf7 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 14:56:19 -0800 Subject: [PATCH 4/6] Use shorter function names (min, max, abs, conj). --- examples/api/collections_demo.py | 7 ++-- examples/api/sankey_demo_old.py | 4 +-- examples/event_handling/poly_editor.py | 4 +-- examples/pylab_examples/anscombe.py | 5 ++- examples/pylab_examples/axes_demo.py | 2 +- examples/pylab_examples/layer_images.py | 4 +-- examples/pylab_examples/line_collection2.py | 4 +-- examples/pylab_examples/multi_image.py | 11 +++---- examples/pylab_examples/quadmesh_demo.py | 3 +- examples/pylab_examples/vline_hline_demo.py | 2 +- examples/user_interfaces/embedding_in_wx3.py | 4 +-- lib/matplotlib/axes/_axes.py | 34 ++++++++++---------- lib/matplotlib/axes/_base.py | 12 +++---- lib/matplotlib/contour.py | 26 ++++----------- lib/matplotlib/legend_handler.py | 2 +- lib/matplotlib/mlab.py | 20 ++++++------ lib/matplotlib/quiver.py | 4 +-- lib/matplotlib/sankey.py | 2 +- lib/matplotlib/tests/test_axes.py | 6 ++-- lib/matplotlib/ticker.py | 6 ++-- 20 files changed, 72 insertions(+), 90 deletions(-) diff --git a/examples/api/collections_demo.py b/examples/api/collections_demo.py index 5b4d3bcd41f6..59997ce3f1c0 100644 --- a/examples/api/collections_demo.py +++ b/examples/api/collections_demo.py @@ -89,9 +89,8 @@ # 7-sided regular polygons -col = collections.RegularPolyCollection(7, - sizes=np.fabs(xx) * 10.0, offsets=xyo, - transOffset=ax3.transData) +col = collections.RegularPolyCollection( + 7, sizes=np.abs(xx) * 10.0, offsets=xyo, transOffset=ax3.transData) trans = transforms.Affine2D().scale(fig.dpi / 72.0) col.set_transform(trans) # the points to pixels transform ax3.add_collection(col, autolim=True) @@ -109,7 +108,7 @@ offs = (0.1, 0.0) yy = np.linspace(0, 2*np.pi, nverts) -ym = np.amax(yy) +ym = np.max(yy) xx = (0.2 + (ym - yy)/ym)**2 * np.cos(yy - 0.4)*0.5 segs = [] for i in range(ncurves): diff --git a/examples/api/sankey_demo_old.py b/examples/api/sankey_demo_old.py index fbe3c5d47ae5..93005feaf79d 100755 --- a/examples/api/sankey_demo_old.py +++ b/examples/api/sankey_demo_old.py @@ -37,11 +37,11 @@ def sankey(ax, import matplotlib.patches as mpatches from matplotlib.path import Path - outs = np.absolute(outputs) + outs = np.abs(outputs) outsigns = np.sign(outputs) outsigns[-1] = 0 # Last output - ins = np.absolute(inputs) + ins = np.abs(inputs) insigns = np.sign(inputs) insigns[0] = 0 # First input diff --git a/examples/event_handling/poly_editor.py b/examples/event_handling/poly_editor.py index 98d65d0021c5..df95a95d11fe 100644 --- a/examples/event_handling/poly_editor.py +++ b/examples/event_handling/poly_editor.py @@ -70,8 +70,8 @@ def get_ind_under_point(self, event): xy = np.asarray(self.poly.xy) xyt = self.poly.get_transform().transform(xy) xt, yt = xyt[:, 0], xyt[:, 1] - d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2) - indseq = np.nonzero(np.equal(d, np.amin(d)))[0] + d = np.hypot(xt - event.x, yt - event.y) + indseq, = np.nonzero(d == d.min()) ind = indseq[0] if d[ind] >= self.epsilon: diff --git a/examples/pylab_examples/anscombe.py b/examples/pylab_examples/anscombe.py index 0c043af34ce4..ba82b8cbca84 100755 --- a/examples/pylab_examples/anscombe.py +++ b/examples/pylab_examples/anscombe.py @@ -22,7 +22,7 @@ def fit(x): return 3 + 0.5*x -xfit = np.array([np.amin(x), np.amax(x)]) +xfit = np.array([np.min(x), np.max(x)]) plt.subplot(221) plt.plot(x, y1, 'ks', xfit, fit(xfit), 'r-', lw=2) @@ -43,8 +43,7 @@ def fit(x): plt.setp(plt.gca(), yticks=(4, 8, 12), xticks=(0, 10, 20)) plt.subplot(224) - -xfit = np.array([np.amin(x4), np.amax(x4)]) +xfit = np.array([np.min(x4), np.max(x4)]) plt.plot(x4, y4, 'ks', xfit, fit(xfit), 'r-', lw=2) plt.axis([2, 20, 2, 14]) plt.setp(plt.gca(), yticklabels=[], yticks=(4, 8, 12), xticks=(0, 10, 20)) diff --git a/examples/pylab_examples/axes_demo.py b/examples/pylab_examples/axes_demo.py index 494ebb4e1692..e30f66e68565 100644 --- a/examples/pylab_examples/axes_demo.py +++ b/examples/pylab_examples/axes_demo.py @@ -14,7 +14,7 @@ # the main axes is subplot(111) by default plt.plot(t, s) -plt.axis([0, 1, 1.1*np.amin(s), 2*np.amax(s)]) +plt.axis([0, 1, 1.1 * np.min(s), 2 * np.max(s)]) plt.xlabel('time (s)') plt.ylabel('current (nA)') plt.title('Gaussian colored noise') diff --git a/examples/pylab_examples/layer_images.py b/examples/pylab_examples/layer_images.py index bd8119b5fa8d..b558063ab33d 100644 --- a/examples/pylab_examples/layer_images.py +++ b/examples/pylab_examples/layer_images.py @@ -23,9 +23,7 @@ def func3(x, y): # for the images their apparent extent could be different due to # interpolation edge effects - -xmin, xmax, ymin, ymax = np.amin(x), np.amax(x), np.amin(y), np.amax(y) -extent = xmin, xmax, ymin, ymax +extent = np.min(x), np.max(x), np.min(y), np.max(y) fig = plt.figure(frameon=False) Z1 = np.add.outer(range(8), range(8)) % 2 # chessboard diff --git a/examples/pylab_examples/line_collection2.py b/examples/pylab_examples/line_collection2.py index 8165ca87eab4..7ddfa38be183 100644 --- a/examples/pylab_examples/line_collection2.py +++ b/examples/pylab_examples/line_collection2.py @@ -13,8 +13,8 @@ # We need to set the plot limits, they will not autoscale ax = plt.axes() -ax.set_xlim((np.amin(x), np.amax(x))) -ax.set_ylim((np.amin(np.amin(ys)), np.amax(np.amax(ys)))) +ax.set_xlim(np.min(x), np.max(x)) +ax.set_ylim(np.min(ys), np.max(ys)) # colors is sequence of rgba tuples # linestyle is a string or dash tuple. Legal string values are diff --git a/examples/pylab_examples/multi_image.py b/examples/pylab_examples/multi_image.py index ebcfc8168448..c9dcc11da14a 100644 --- a/examples/pylab_examples/multi_image.py +++ b/examples/pylab_examples/multi_image.py @@ -7,8 +7,7 @@ from matplotlib.pyplot import figure, show, axes, sci from matplotlib import cm, colors from matplotlib.font_manager import FontProperties -from numpy import amin, amax, ravel -from numpy.random import rand +import numpy as np Nr = 3 Nc = 2 @@ -37,12 +36,12 @@ a.set_xticklabels([]) # Make some fake data with a range that varies # somewhat from one plot to the next. - data = ((1 + i + j)/10.0)*rand(10, 20)*1e-6 - dd = ravel(data) + data = ((1 + i + j) / 10) * np.random.rand(10, 20) * 1e-6 + dd = data.ravel() # Manually find the min and max of all colors for # use in setting the color scale. - vmin = min(vmin, amin(dd)) - vmax = max(vmax, amax(dd)) + vmin = min(vmin, np.min(dd)) + vmax = max(vmax, np.max(dd)) images.append(a.imshow(data, cmap=cmap)) ax.append(a) diff --git a/examples/pylab_examples/quadmesh_demo.py b/examples/pylab_examples/quadmesh_demo.py index 8f6ab8ae189a..7ad1b8e3144f 100755 --- a/examples/pylab_examples/quadmesh_demo.py +++ b/examples/pylab_examples/quadmesh_demo.py @@ -21,8 +21,7 @@ Z = (Z - Z.min()) / (Z.max() - Z.min()) # The color array can include masked values: -Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z) - +Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z) fig = figure() ax = fig.add_subplot(121) diff --git a/examples/pylab_examples/vline_hline_demo.py b/examples/pylab_examples/vline_hline_demo.py index d4fe9e0bf306..63f71dff4173 100644 --- a/examples/pylab_examples/vline_hline_demo.py +++ b/examples/pylab_examples/vline_hline_demo.py @@ -10,7 +10,7 @@ def f(t): s1 = np.sin(2 * np.pi * t) e1 = np.exp(-t) - return np.absolute((s1 * e1)) + .05 + return np.abs(s1 * e1) + .05 t = np.arange(0.0, 5.0, 0.1) s = f(t) diff --git a/examples/user_interfaces/embedding_in_wx3.py b/examples/user_interfaces/embedding_in_wx3.py index 76cd4196c513..99894a67e83d 100755 --- a/examples/user_interfaces/embedding_in_wx3.py +++ b/examples/user_interfaces/embedding_in_wx3.py @@ -74,7 +74,7 @@ def init_plot_data(self): z = np.sin(self.x) + np.cos(self.y) self.im = a.imshow(z, cmap=cm.RdBu) # , interpolation='nearest') - zmax = np.amax(z) - ERR_TOL + zmax = np.max(z) - ERR_TOL ymax_i, xmax_i = np.nonzero(z >= zmax) if self.im.origin == 'upper': ymax_i = z.shape[0] - ymax_i @@ -93,7 +93,7 @@ def OnWhiz(self, evt): z = np.sin(self.x) + np.cos(self.y) self.im.set_array(z) - zmax = np.amax(z) - ERR_TOL + zmax = np.max(z) - ERR_TOL ymax_i, xmax_i = np.nonzero(z >= zmax) if self.im.origin == 'upper': ymax_i = z.shape[0] - ymax_i diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index cb2797134f00..5f48f9356d6f 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2460,7 +2460,7 @@ def stem(self, *args, **kwargs): marker=linemarker, label="_nolegend_") stemlines.append(l) - baseline, = self.plot([np.amin(x), np.amax(x)], [bottom, bottom], + baseline, = self.plot([np.min(x), np.max(x)], [bottom, bottom], color=basecolor, linestyle=basestyle, marker=basemarker, label="_nolegend_") @@ -4228,8 +4228,8 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, if extent is not None: xmin, xmax, ymin, ymax = extent else: - xmin, xmax = (np.amin(x), np.amax(x)) if len(x) else (0, 1) - ymin, ymax = (np.amin(y), np.amax(y)) if len(y) else (0, 1) + xmin, xmax = (np.min(x), np.max(x)) if len(x) else (0, 1) + ymin, ymax = (np.min(y), np.max(y)) if len(y) else (0, 1) # to avoid issues with singular data, expand the min/max pairs xmin, xmax = mtrans.nonsingular(xmin, xmax, expander=0.1) @@ -5470,10 +5470,10 @@ def pcolor(self, *args, **kwargs): self.add_collection(collection, autolim=False) - minx = np.amin(x) - maxx = np.amax(x) - miny = np.amin(y) - maxy = np.amax(y) + minx = np.min(x) + maxx = np.max(x) + miny = np.min(y) + maxy = np.max(y) collection.sticky_edges.x[:] = [minx, maxx] collection.sticky_edges.y[:] = [miny, maxy] corners = (minx, miny), (maxx, maxy) @@ -5622,10 +5622,10 @@ def pcolormesh(self, *args, **kwargs): self.add_collection(collection, autolim=False) - minx = np.amin(X) - maxx = np.amax(X) - miny = np.amin(Y) - maxy = np.amax(Y) + minx = np.min(X) + maxx = np.max(X) + miny = np.min(Y) + maxy = np.max(Y) collection.sticky_edges.x[:] = [minx, maxx] collection.sticky_edges.y[:] = [miny, maxy] corners = (minx, miny), (maxx, maxy) @@ -6386,7 +6386,7 @@ def _normalize_input(inp, ename='input'): else: labels = [six.text_type(lab) for lab in label] - for (patch, lbl) in zip_longest(patches, labels, fillvalue=None): + for patch, lbl in zip_longest(patches, labels, fillvalue=None): if patch: p = patch[0] p.update(kwargs) @@ -6724,7 +6724,7 @@ def csd(self, x, y, NFFT=None, Fs=None, Fc=None, detrend=None, # pxy is complex freqs += Fc - line = self.plot(freqs, 10 * np.log10(np.absolute(pxy)), **kwargs) + line = self.plot(freqs, 10 * np.log10(np.abs(pxy)), **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Cross Spectrum Magnitude (dB)') self.grid(True) @@ -7227,7 +7227,7 @@ def specgram(self, x, NFFT=None, Fs=None, Fc=None, detrend=None, Z = np.flipud(Z) if xextent is None: - xextent = 0, np.amax(t) + xextent = 0, np.max(t) xmin, xmax = xextent freqs += Fc extent = xmin, xmax, freqs[0], freqs[-1] @@ -7300,7 +7300,7 @@ def spy(self, Z, precision=0, marker=None, markersize=None, marker = 's' if marker is None and markersize is None: Z = np.asarray(Z) - mask = np.absolute(Z) > precision + mask = np.abs(Z) > precision if 'cmap' not in kwargs: kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], @@ -7316,12 +7316,12 @@ def spy(self, Z, precision=0, marker=None, markersize=None, y = c.row x = c.col else: - nonzero = np.absolute(c.data) > precision + nonzero = np.abs(c.data) > precision y = c.row[nonzero] x = c.col[nonzero] else: Z = np.asarray(Z) - nonzero = np.absolute(Z) > precision + nonzero = np.abs(Z) > precision y, x = np.nonzero(nonzero) if marker is None: marker = 's' diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index 542d0be57f5f..c9c027b649a2 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -1346,8 +1346,8 @@ def get_data_ratio(self): xmin, xmax = self.get_xbound() ymin, ymax = self.get_ybound() - xsize = max(math.fabs(xmax - xmin), 1e-30) - ysize = max(math.fabs(ymax - ymin), 1e-30) + xsize = max(abs(xmax - xmin), 1e-30) + ysize = max(abs(ymax - ymin), 1e-30) return ysize / xsize @@ -1359,8 +1359,8 @@ def get_data_ratio_log(self): xmin, xmax = self.get_xbound() ymin, ymax = self.get_ybound() - xsize = max(math.fabs(math.log10(xmax) - math.log10(xmin)), 1e-30) - ysize = max(math.fabs(math.log10(ymax) - math.log10(ymin)), 1e-30) + xsize = max(abs(math.log10(xmax) - math.log10(xmin)), 1e-30) + ysize = max(abs(math.log10(ymax) - math.log10(ymin)), 1e-30) return ysize / xsize @@ -1432,8 +1432,8 @@ def apply_aspect(self, position=None): xmin, xmax = math.log10(xmin), math.log10(xmax) ymin, ymax = math.log10(ymin), math.log10(ymax) - xsize = max(math.fabs(xmax - xmin), 1e-30) - ysize = max(math.fabs(ymax - ymin), 1e-30) + xsize = max(abs(xmax - xmin), 1e-30) + ysize = max(abs(ymax - ymin), 1e-30) l, b, w, h = position.bounds box_aspect = fig_aspect * (h / w) diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index e1cb1f1bf257..46a02c1b3a00 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -226,20 +226,8 @@ def clabel(self, *args, **kwargs): def print_label(self, linecontour, labelwidth): "Return *False* if contours are too short for a label." - lcsize = len(linecontour) - if lcsize > 10 * labelwidth: - return True - - xmax = np.amax(linecontour[:, 0]) - xmin = np.amin(linecontour[:, 0]) - ymax = np.amax(linecontour[:, 1]) - ymin = np.amin(linecontour[:, 1]) - - lw = labelwidth - if (xmax - xmin) > 1.2 * lw or (ymax - ymin) > 1.2 * lw: - return True - else: - return False + return (len(linecontour) > 10 * labelwidth + or (np.ptp(linecontour, axis=0) > 1.2 * labelwidth).any()) def too_close(self, x, y, lw): "Return *True* if a label is already near this location." @@ -1056,8 +1044,8 @@ def _process_args(self, *args, **kwargs): self.levels = args[0] self.allsegs = args[1] self.allkinds = len(args) > 2 and args[2] or None - self.zmax = np.amax(self.levels) - self.zmin = np.amin(self.levels) + self.zmax = np.max(self.levels) + self.zmin = np.min(self.levels) self._auto = False # Check lengths of levels and allsegs. @@ -1180,7 +1168,7 @@ def _contour_level_args(self, z, args): if self.filled and len(self.levels) < 2: raise ValueError("Filled contours require at least 2 levels.") - if len(self.levels) > 1 and np.amin(np.diff(self.levels)) <= 0.0: + if len(self.levels) > 1 and np.min(np.diff(self.levels)) <= 0.0: if hasattr(self, '_corner_mask') and self._corner_mask == 'legacy': warnings.warn("Contour levels are not increasing") else: @@ -1210,8 +1198,8 @@ def _process_levels(self): with line contours. """ # following are deprecated and will be removed in 2.2 - self._vmin = np.amin(self.levels) - self._vmax = np.amax(self.levels) + self._vmin = np.min(self.levels) + self._vmax = np.max(self.levels) # Make a private _levels to include extended regions; we # want to leave the original levels attribute unchanged. diff --git a/lib/matplotlib/legend_handler.py b/lib/matplotlib/legend_handler.py index 8c0baffc6230..2509e330f974 100644 --- a/lib/matplotlib/legend_handler.py +++ b/lib/matplotlib/legend_handler.py @@ -551,7 +551,7 @@ def create_artists(self, legend, orig_handle, for lm, m in zip(leg_stemlines, stemlines): self.update_prop(lm, m, legend) - leg_baseline = Line2D([np.amin(xdata), np.amax(xdata)], + leg_baseline = Line2D([np.min(xdata), np.max(xdata)], [bottom, bottom]) self.update_prop(leg_baseline, baseline, legend) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 4390e54bf561..e579f53fb0c6 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -723,11 +723,11 @@ def _spectral_helper(x, y=None, NFFT=None, Fs=None, detrend_func=None, resultY = apply_window(resultY, window, axis=0) resultY = detrend(resultY, detrend_func, axis=0) resultY = np.fft.fft(resultY, n=pad_to, axis=0)[:numFreqs, :] - result = np.conjugate(result) * resultY + result = np.conj(result) * resultY elif mode == 'psd': - result = np.conjugate(result) * result + result = np.conj(result) * result elif mode == 'magnitude': - result = np.absolute(result) + result = np.abs(result) elif mode == 'angle' or mode == 'phase': # we unwrap the phase later to handle the onesided vs. twosided case result = np.angle(result) @@ -1470,7 +1470,7 @@ def cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=detrend_none, FFTSlices[iCol] = Slices if preferSpeedOverMemory: - FFTConjSlices[iCol] = np.conjugate(Slices) + FFTConjSlices[iCol] = np.conj(Slices) Pxx[iCol] = np.divide(np.mean(abs(Slices)**2, axis=0), normVal) del Slices, ind, windowVals @@ -1488,7 +1488,7 @@ def cohere_pairs(X, ij, NFFT=256, Fs=2, detrend=detrend_none, if preferSpeedOverMemory: Pxy = FFTSlices[i] * FFTConjSlices[j] else: - Pxy = FFTSlices[i] * np.conjugate(FFTSlices[j]) + Pxy = FFTSlices[i] * np.conj(FFTSlices[j]) if numSlices > 1: Pxy = np.mean(Pxy, axis=0) # Pxy = np.divide(Pxy, normVal) @@ -2080,7 +2080,7 @@ def rms_flat(a): """ Return the root mean square of all the elements of *a*, flattened out. """ - return np.sqrt(np.mean(np.absolute(a)**2)) + return np.sqrt(np.mean(np.abs(a) ** 2)) def l1norm(a): @@ -2089,7 +2089,7 @@ def l1norm(a): Implemented as a separate function (not a call to :func:`norm` for speed). """ - return np.sum(np.absolute(a)) + return np.sum(np.abs(a)) def l2norm(a): @@ -2098,7 +2098,7 @@ def l2norm(a): Implemented as a separate function (not a call to :func:`norm` for speed). """ - return np.sqrt(np.sum(np.absolute(a)**2)) + return np.sqrt(np.sum(np.abs(a) ** 2)) def norm_flat(a, p=2): @@ -2113,9 +2113,9 @@ def norm_flat(a, p=2): # This function was being masked by a more general norm later in # the file. We may want to simply delete it. if p == 'Infinity': - return np.amax(np.absolute(a)) + return np.max(np.abs(a)) else: - return (np.sum(np.absolute(a)**p))**(1.0/p) + return np.sum(np.abs(a) ** p) ** (1 / p) def frange(xini, xfin=None, delta=None, **kw): diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py index 557966d5da6f..fc6e3195c3bc 100644 --- a/lib/matplotlib/quiver.py +++ b/lib/matplotlib/quiver.py @@ -607,7 +607,7 @@ def _angles_lengths(self, U, V, eps=1): xyp = self.ax.transData.transform(self.XY + eps * uv) dxy = xyp - xy angles = np.arctan2(dxy[:, 1], dxy[:, 0]) - lengths = np.absolute(dxy[:, 0] + dxy[:, 1] * 1j) / eps + lengths = np.hypot(*dxy.T) / eps return angles, lengths def _make_verts(self, U, V): @@ -627,7 +627,7 @@ def _make_verts(self, U, V): if self.scale_units == 'xy': a = lengths else: - a = np.absolute(uv) + a = np.abs(uv) if self.scale is None: sn = max(10, math.sqrt(self.N)) if self.Umask is not ma.nomask: diff --git a/lib/matplotlib/sankey.py b/lib/matplotlib/sankey.py index 7099814825e2..c822f419122f 100644 --- a/lib/matplotlib/sankey.py +++ b/lib/matplotlib/sankey.py @@ -494,7 +494,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', raise ValueError( "trunklength is negative.\nThis isn't allowed, because it would " "cause poor layout.") - if np.absolute(np.sum(flows)) > self.tolerance: + if np.abs(np.sum(flows)) > self.tolerance: verbose.report( "The sum of the flows is nonzero (%f).\nIs the " "system not at steady state?" % np.sum(flows), 'helpful') diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 5c426ee3d2d2..355ef9b5ea7f 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -805,11 +805,11 @@ def test_pcolormesh(): Qx = np.cos(Y) - np.cos(X) Qz = np.sin(Y) + np.sin(X) Qx = (Qx + 1.1) - Z = np.sqrt(X**2 + Y**2)/5 - Z = (Z - Z.min()) / (Z.max() - Z.min()) + Z = np.hypot(X, Y) / 5 + Z = (Z - Z.min()) / Z.ptp() # The color array can include masked values: - Zm = ma.masked_where(np.fabs(Qz) < 0.5*np.amax(Qz), Z) + Zm = ma.masked_where(np.abs(Qz) < 0.5 * np.max(Qz), Z) fig = plt.figure() ax = fig.add_subplot(131) diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index a0a835b662d6..e55fdbfa2129 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -732,7 +732,7 @@ def _set_orderOfMagnitude(self, range): if not self._scientific: self.orderOfMagnitude = 0 return - locs = np.absolute(self.locs) + locs = np.abs(self.locs) if self.offset: oom = math.floor(math.log10(range)) else: @@ -788,7 +788,7 @@ def _set_format(self, vmin, vmax): def pprint_val(self, x): xp = (x - self.offset) / (10. ** self.orderOfMagnitude) - if np.absolute(xp) < 1e-8: + if np.abs(xp) < 1e-8: xp = 0 if self._useLocale: return locale.format_string(self.format, (xp,)) @@ -1535,7 +1535,7 @@ def tick_values(self, vmin, vmax): ticks = self.locs[::step] for i in range(1, step): ticks1 = self.locs[i::step] - if np.absolute(ticks1).min() < np.absolute(ticks).min(): + if np.abs(ticks1).min() < np.abs(ticks).min(): ticks = ticks1 return self.raise_if_exceeds(ticks) From 69622dd32de172be82c10a03cfd43d49d940cf8a Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Wed, 30 Nov 2016 23:00:14 -0800 Subject: [PATCH 5/6] set/dict literals/comprehensions. --- boilerplate.py | 2 +- doc/sphinxext/gen_gallery.py | 10 ++++------ examples/pylab_examples/arrow_demo.py | 4 ++-- examples/tests/backend_driver.py | 5 ++--- lib/matplotlib/__init__.py | 6 +++--- lib/matplotlib/axes/_base.py | 6 +++--- lib/matplotlib/axis.py | 6 +++--- lib/matplotlib/backends/backend_gtk.py | 19 ++++++++----------- lib/matplotlib/backends/backend_pdf.py | 9 ++++----- .../backends/qt_editor/formlayout.py | 2 +- lib/matplotlib/cbook.py | 8 ++++---- lib/matplotlib/figure.py | 2 +- lib/matplotlib/font_manager.py | 16 ++++++++-------- lib/matplotlib/gridspec.py | 8 ++------ lib/matplotlib/image.py | 2 +- lib/matplotlib/mathtext.py | 2 +- lib/matplotlib/mlab.py | 4 ++-- lib/matplotlib/patches.py | 2 +- lib/matplotlib/pyplot.py | 6 +++--- lib/matplotlib/rcsetup.py | 6 ++---- lib/matplotlib/style/core.py | 4 ++-- lib/matplotlib/tests/test_cbook.py | 2 +- lib/matplotlib/tests/test_ticker.py | 2 +- lib/matplotlib/texmanager.py | 2 +- lib/matplotlib/textpath.py | 8 ++++---- lib/matplotlib/ticker.py | 2 +- lib/mpl_toolkits/axes_grid1/parasite_axes.py | 4 ++-- lib/mpl_toolkits/gtktools.py | 7 +------ lib/mpl_toolkits/mplot3d/axes3d.py | 2 +- 29 files changed, 70 insertions(+), 88 deletions(-) diff --git a/boilerplate.py b/boilerplate.py index 5aab3b0af9da..6aabc83cb892 100644 --- a/boilerplate.py +++ b/boilerplate.py @@ -317,7 +317,7 @@ def format_value(value): # A gensym-like facility in case some function takes an # argument named washold, ax, or ret washold, ret, ax = 'washold', 'ret', 'ax' - bad = set(args) | set((varargs, varkw)) + bad = set(args) | {varargs, varkw} while washold in bad or ret in bad or ax in bad: washold = 'washold' + str(random.randrange(10 ** 12)) ret = 'ret' + str(random.randrange(10 ** 12)) diff --git a/doc/sphinxext/gen_gallery.py b/doc/sphinxext/gen_gallery.py index 74544ae66595..520bb958d87b 100644 --- a/doc/sphinxext/gen_gallery.py +++ b/doc/sphinxext/gen_gallery.py @@ -76,12 +76,10 @@ def gen_gallery(app, doctree): # images we want to skip for the gallery because they are an unusual # size that doesn't layout well in a table, or because they may be # redundant with other images or uninteresting - skips = set([ - 'mathtext_examples', - 'matshow_02', - 'matshow_03', - 'matplotlib_icon', - ]) + skips = {'mathtext_examples', + 'matshow_02', + 'matshow_03', + 'matplotlib_icon'} thumbnails = {} rows = [] diff --git a/examples/pylab_examples/arrow_demo.py b/examples/pylab_examples/arrow_demo.py index 73781f5f1e65..fb2e0a4c06c5 100644 --- a/examples/pylab_examples/arrow_demo.py +++ b/examples/pylab_examples/arrow_demo.py @@ -14,8 +14,8 @@ rates_to_bases = {'r1': 'AT', 'r2': 'TA', 'r3': 'GA', 'r4': 'AG', 'r5': 'CA', 'r6': 'AC', 'r7': 'GT', 'r8': 'TG', 'r9': 'CT', 'r10': 'TC', 'r11': 'GC', 'r12': 'CG'} -numbered_bases_to_rates = dict([(v, k) for k, v in rates_to_bases.items()]) -lettered_bases_to_rates = dict([(v, 'r' + v) for k, v in rates_to_bases.items()]) +numbered_bases_to_rates = {v: k for k, v in rates_to_bases.items()} +lettered_bases_to_rates = {v: 'r' + v for k, v in rates_to_bases.items()} def add_dicts(d1, d2): diff --git a/examples/tests/backend_driver.py b/examples/tests/backend_driver.py index 84fe6b1809fd..8e8bc7beec73 100755 --- a/examples/tests/backend_driver.py +++ b/examples/tests/backend_driver.py @@ -321,14 +321,13 @@ def report_missing(dir, flist): globstr = os.path.join(dir, '*.py') fnames = glob.glob(globstr) - pyfiles = set([os.path.split(fullpath)[-1] for fullpath in set(fnames)]) + pyfiles = {os.path.split(fullpath)[-1] for fullpath in set(fnames)} exclude = set(excluded.get(dir, [])) flist = set(flist) missing = list(pyfiles - flist - exclude) - missing.sort() if missing: - print('%s files not tested: %s' % (dir, ', '.join(missing))) + print('%s files not tested: %s' % (dir, ', '.join(sorted(missing)))) def report_all_missing(directories): diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 4159acf4ba25..9d9cbd1ae554 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -263,7 +263,7 @@ class Verbose(object): instance to handle the output. Default is sys.stdout """ levels = ('silent', 'helpful', 'debug', 'debug-annoying') - vald = dict([(level, i) for i, level in enumerate(levels)]) + vald = {level: i for i, level in enumerate(levels)} # parse the verbosity from the command line; flags look like # --verbose-silent or --verbose-helpful @@ -860,10 +860,10 @@ def matplotlib_fname(): _deprecated_ignore_map = { } -_obsolete_set = set(['tk.pythoninspect', 'legend.isaxes']) +_obsolete_set = {'tk.pythoninspect', 'legend.isaxes'} # The following may use a value of None to suppress the warning. -_deprecated_set = set(['axes.hold']) # do NOT include in _all_deprecated +_deprecated_set = {'axes.hold'} # do NOT include in _all_deprecated _all_deprecated = set(chain(_deprecated_ignore_map, _deprecated_map, diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index c9c027b649a2..363d1c6fece3 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -263,7 +263,7 @@ def _getdefaults(self, ignore, *kwargs): """ prop_keys = self._prop_keys if ignore is None: - ignore = set([]) + ignore = set() prop_keys = prop_keys - ignore if any(all(kw.get(k, None) is None for kw in kwargs) @@ -309,8 +309,8 @@ def _makefill(self, x, y, kw, kwargs): # *user* explicitly specifies a marker which should be an error. # We also want to prevent advancing the cycler if there are no # defaults needed after ignoring the given properties. - ignores = set(['marker', 'markersize', 'markeredgecolor', - 'markerfacecolor', 'markeredgewidth']) + ignores = {'marker', 'markersize', 'markeredgecolor', + 'markerfacecolor', 'markeredgewidth'} # Also ignore anything provided by *kwargs*. for k, v in six.iteritems(kwargs): if v is not None: diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index f73d0f370e9c..ed3b4450490f 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -324,8 +324,8 @@ def _apply_params(self, **kw): self.label1.set_transform(trans) trans = self._get_text2_transform()[0] self.label2.set_transform(trans) - tick_kw = dict([kv for kv in six.iteritems(kw) - if kv[0] in ['color', 'zorder']]) + tick_kw = {k: v for k, v in six.iteritems(kw) + if k in ['color', 'zorder']} if tick_kw: self.tick1line.set(**tick_kw) self.tick2line.set(**tick_kw) @@ -334,7 +334,7 @@ def _apply_params(self, **kw): label_list = [k for k in six.iteritems(kw) if k[0] in ['labelsize', 'labelcolor', 'labelrotation']] if label_list: - label_kw = dict([(k[5:], v) for (k, v) in label_list]) + label_kw = {k[5:]: v for k, v in label_list} self.label1.set(**label_kw) self.label2.set(**label_kw) for k, v in six.iteritems(label_kw): diff --git a/lib/matplotlib/backends/backend_gtk.py b/lib/matplotlib/backends/backend_gtk.py index b2906eddb82e..39b3e7b78b1d 100644 --- a/lib/matplotlib/backends/backend_gtk.py +++ b/lib/matplotlib/backends/backend_gtk.py @@ -905,12 +905,11 @@ class DialogLineprops(object): ) linestyles = [ls for ls in lines.Line2D.lineStyles if ls.strip()] - linestyled = dict([ (s,i) for i,s in enumerate(linestyles)]) + linestyled = {s: i for i, s in enumerate(linestyles)} - - markers = [m for m in markers.MarkerStyle.markers if cbook.is_string_like(m)] - - markerd = dict([(s,i) for i,s in enumerate(markers)]) + markers = [m for m in markers.MarkerStyle.markers + if cbook.is_string_like(m)] + markerd = {s: i for i, s in enumerate(markers)} def __init__(self, lines): import gtk.glade @@ -918,12 +917,14 @@ def __init__(self, lines): datadir = matplotlib.get_data_path() gladefile = os.path.join(datadir, 'lineprops.glade') if not os.path.exists(gladefile): - raise IOError('Could not find gladefile lineprops.glade in %s'%datadir) + raise IOError( + 'Could not find gladefile lineprops.glade in %s' % datadir) self._inited = False self._updateson = True # suppress updates when setting widgets manually self.wtree = gtk.glade.XML(gladefile, 'dialog_lineprops') - self.wtree.signal_autoconnect(dict([(s, getattr(self, s)) for s in self.signals])) + self.wtree.signal_autoconnect( + {s: getattr(self, s) for s in self.signals}) self.dlg = self.wtree.get_widget('dialog_lineprops') @@ -947,7 +948,6 @@ def __init__(self, lines): self._lastcnt = 0 self._inited = True - def show(self): 'populate the combo box' self._updateson = False @@ -971,7 +971,6 @@ def get_active_line(self): line = self.lines[ind] return line - def get_active_linestyle(self): 'get the active lineinestyle' ind = self.cbox_linestyles.get_active() @@ -1005,8 +1004,6 @@ def _update(self): line.figure.canvas.draw() - - def on_combobox_lineprops_changed(self, item): 'update the widgets from the active line' if not self._inited: return diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 74378031fa8f..797429a6a296 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -318,8 +318,7 @@ def pdfRepr(self): grestore=b'Q', textpos=b'Td', selectfont=b'Tf', textmatrix=b'Tm', show=b'Tj', showkern=b'TJ', setlinewidth=b'w', clip=b'W', shading=b'sh') -Op = Bunch(**dict([(name, Operator(value)) - for name, value in six.iteritems(_pdfops)])) +Op = Bunch(**{name: Operator(value) for name, value in six.iteritems(_pdfops)}) def _paint_path(fill, stroke): @@ -556,9 +555,9 @@ def close(self): self.endStream() # Write out the various deferred objects self.writeFonts() - self.writeObject(self.alphaStateObject, - dict([(val[0], val[1]) - for val in six.itervalues(self.alphaStates)])) + self.writeObject( + self.alphaStateObject, + {val[0]: val[1] for val in six.itervalues(self.alphaStates)}) self.writeHatches() self.writeGouraudTriangles() xobjects = dict(x[1:] for x in six.itervalues(self._images)) diff --git a/lib/matplotlib/backends/qt_editor/formlayout.py b/lib/matplotlib/backends/qt_editor/formlayout.py index 00a1a03a36ee..25b03d0316d4 100644 --- a/lib/matplotlib/backends/qt_editor/formlayout.py +++ b/lib/matplotlib/backends/qt_editor/formlayout.py @@ -56,7 +56,7 @@ from matplotlib.backends.qt_compat import QtGui, QtWidgets, QtCore -BLACKLIST = set(["title", "label"]) +BLACKLIST = {"title", "label"} class ColorButton(QtWidgets.QPushButton): diff --git a/lib/matplotlib/cbook.py b/lib/matplotlib/cbook.py index 3038f47d6a81..9939a3d55126 100644 --- a/lib/matplotlib/cbook.py +++ b/lib/matplotlib/cbook.py @@ -658,7 +658,7 @@ def __repr__(self): def unique(x): """Return a list of unique elements of *x*""" - return list(six.iterkeys(dict([(val, 1) for val in x]))) + return list(set(x)) def iterable(obj): @@ -1407,7 +1407,7 @@ def finddir(o, match, case=False): def reverse_dict(d): """reverse the dictionary -- may lose data if values are not unique!""" - return dict([(v, k) for k, v in six.iteritems(d)]) + return {v: k for k, v in six.iteritems(d)} def restrict_dict(d, keys): @@ -1415,7 +1415,7 @@ def restrict_dict(d, keys): Return a dictionary that contains those keys that appear in both d and keys, with values from d. """ - return dict([(k, v) for (k, v) in six.iteritems(d) if k in keys]) + return {k: v for k, v in six.iteritems(d) if k in keys} def report_memory(i=0): # argument may go away @@ -2077,7 +2077,7 @@ def unmasked_index_ranges(mask, compressed=True): # The ls_mapper maps short codes for line style to their full name used # by backends # The reverse mapper is for mapping full names to short ones -ls_mapper_r = dict([(ls[1], ls[0]) for ls in _linestyles]) +ls_mapper_r = reverse_dict(ls_mapper) def align_iterators(func, *iterables): diff --git a/lib/matplotlib/figure.py b/lib/matplotlib/figure.py index 8029a43043bb..a9260f515026 100644 --- a/lib/matplotlib/figure.py +++ b/lib/matplotlib/figure.py @@ -95,7 +95,7 @@ def get(self, key): return item[1] def _entry_from_axes(self, e): - ind, k = dict([(a, (ind, k)) for (k, (ind, a)) in self._elements])[e] + ind, k = {a: (ind, k) for k, (ind, a) in self._elements}[e] return (k, (ind, e)) def remove(self, a): diff --git a/lib/matplotlib/font_manager.py b/lib/matplotlib/font_manager.py index f9cfb1600cb6..d2a946688ac3 100644 --- a/lib/matplotlib/font_manager.py +++ b/lib/matplotlib/font_manager.py @@ -108,14 +108,14 @@ 'extra bold' : 800, 'black' : 900} -font_family_aliases = set([ - 'serif', - 'sans-serif', - 'sans serif', - 'cursive', - 'fantasy', - 'monospace', - 'sans']) +font_family_aliases = { + 'serif', + 'sans-serif', + 'sans serif', + 'cursive', + 'fantasy', + 'monospace', + 'sans'} # OS Font paths MSFolders = \ diff --git a/lib/matplotlib/gridspec.py b/lib/matplotlib/gridspec.py index bf2afb72adfc..5476c5dfbe2d 100644 --- a/lib/matplotlib/gridspec.py +++ b/lib/matplotlib/gridspec.py @@ -255,8 +255,6 @@ def update(self, **kwargs): ax.update_params() ax.set_position(ax.figbox) - - def get_subplot_params(self, fig=None): """ return a dictionary of subplot layout parameters. The default @@ -265,13 +263,12 @@ def get_subplot_params(self, fig=None): from matplotlib.figure import SubplotParams import copy if fig is None: - kw = dict([(k, rcParams["figure.subplot."+k]) \ - for k in self._AllowedKeys]) + kw = {k: rcParams["figure.subplot."+k] for k in self._AllowedKeys} subplotpars = SubplotParams(**kw) else: subplotpars = copy.copy(fig.subplotpars) - update_kw = dict([(k, getattr(self, k)) for k in self._AllowedKeys]) + update_kw = {k: getattr(self, k) for k in self._AllowedKeys} subplotpars.update(**update_kw) return subplotpars @@ -428,7 +425,6 @@ def get_position(self, fig, return_all=False): figBottoms, figTops, figLefts, figRights = \ gridspec.get_grid_positions(fig) - rowNum, colNum = divmod(self.num1, ncols) figBottom = figBottoms[rowNum] figTop = figTops[rowNum] diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 3cb306fb9371..9e4529fa0109 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -186,7 +186,7 @@ class _ImageBase(martist.Artist, cm.ScalarMappable): # backward compatibility just in case. _interpd = _interpd_ # reverse interp dict - _interpdr = dict([(v, k) for k, v in six.iteritems(_interpd_)]) + _interpdr = {v: k for k, v in six.iteritems(_interpd_)} iterpnames = interpolations_names # diff --git a/lib/matplotlib/mathtext.py b/lib/matplotlib/mathtext.py index 5db875afeae3..5a0923592581 100644 --- a/lib/matplotlib/mathtext.py +++ b/lib/matplotlib/mathtext.py @@ -2410,7 +2410,7 @@ def __init__(self): p.ambi_delim <<= oneOf(list(self._ambi_delim)) p.left_delim <<= oneOf(list(self._left_delim)) p.right_delim <<= oneOf(list(self._right_delim)) - p.right_delim_safe <<= oneOf(list(self._right_delim - set(['}'])) + [r'\}']) + p.right_delim_safe <<= oneOf(list(self._right_delim - {'}'}) + [r'\}']) p.genfrac <<= Group( Suppress(Literal(r"\genfrac")) diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index e579f53fb0c6..c2fea2219271 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -2495,8 +2495,8 @@ def rec_join(key, r1, r2, jointype='inner', defaults=None, r1postfix='1', def makekey(row): return tuple([row[name] for name in key]) - r1d = dict([(makekey(row), i) for i, row in enumerate(r1)]) - r2d = dict([(makekey(row), i) for i, row in enumerate(r2)]) + r1d = {makekey(row): i for i, row in enumerate(r1)} + r2d = {makekey(row): i for i, row in enumerate(r2)} r1keys = set(r1d.keys()) r2keys = set(r2d.keys()) diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 8edc5976ead4..ad17fbbe3927 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -1867,7 +1867,7 @@ def __new__(self, stylename, **kw): try: _args_pair = [cs.split("=") for cs in _list[1:]] - _args = dict([(k, float(v)) for k, v in _args_pair]) + _args = {k: float(v) for k, v in _args_pair} except ValueError: raise ValueError("Incorrect style argument : %s" % stylename) _args.update(kw) diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index e148b054c460..21ae8093b962 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -1797,9 +1797,9 @@ def get_plot_commands(): import inspect - exclude = set(['colormaps', 'colors', 'connect', 'disconnect', - 'get_plot_commands', 'get_current_fig_manager', - 'ginput', 'plotting', 'waitforbuttonpress']) + exclude = {'colormaps', 'colors', 'connect', 'disconnect', + 'get_plot_commands', 'get_current_fig_manager', 'ginput', + 'plotting', 'waitforbuttonpress'} exclude |= set(colormaps()) this_module = inspect.getmodule(get_plot_commands) diff --git a/lib/matplotlib/rcsetup.py b/lib/matplotlib/rcsetup.py index 25526cb6da24..39627ce99c3f 100644 --- a/lib/matplotlib/rcsetup.py +++ b/lib/matplotlib/rcsetup.py @@ -62,7 +62,7 @@ def func(s): return s.lower() else: return s - self.valid = dict([(func(k), k) for k in valid]) + self.valid = {func(k): k for k in valid} def __call__(self, s): if self.ignorecase: @@ -683,9 +683,7 @@ def validate_hatch(s): """ if not isinstance(s, six.string_types): raise ValueError("Hatch pattern must be a string") - unique_chars = set(s) - unknown = (unique_chars - - set(['\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'])) + unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'} if unknown: raise ValueError("Unknown hatch symbol(s): %s" % list(unknown)) return s diff --git a/lib/matplotlib/style/core.py b/lib/matplotlib/style/core.py index b1bc691d4057..098f45d5b426 100644 --- a/lib/matplotlib/style/core.py +++ b/lib/matplotlib/style/core.py @@ -36,11 +36,11 @@ # A list of rcParams that should not be applied from styles -STYLE_BLACKLIST = set([ +STYLE_BLACKLIST = { 'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', 'toolbar', 'timezone', 'datapath', 'figure.max_open_warning', - 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy']) + 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'} def _remove_blacklisted_style_params(d, warn=True): diff --git a/lib/matplotlib/tests/test_cbook.py b/lib/matplotlib/tests/test_cbook.py index ca31592ede20..16896d1e48a8 100644 --- a/lib/matplotlib/tests/test_cbook.py +++ b/lib/matplotlib/tests/test_cbook.py @@ -63,7 +63,7 @@ def test_restrict_dict(): assert d3 == {'foo': 'bar'} d4 = cbook.restrict_dict(d, {}) assert d4 == {} - d5 = cbook.restrict_dict(d, set(['foo', 2])) + d5 = cbook.restrict_dict(d, {'foo', 2}) assert d5 == {'foo': 'bar'} # check that d was not modified assert d == {'foo': 'bar', 1: 2} diff --git a/lib/matplotlib/tests/test_ticker.py b/lib/matplotlib/tests/test_ticker.py index d46a067088f1..b86b09fcc7ce 100644 --- a/lib/matplotlib/tests/test_ticker.py +++ b/lib/matplotlib/tests/test_ticker.py @@ -340,7 +340,7 @@ def test_LogFormatterSciNotation(): for base in test_cases.keys(): formatter = mticker.LogFormatterSciNotation(base=base) - formatter.sublabel = set([1, 2, 5, 1.2]) + formatter.sublabel = {1, 2, 5, 1.2} for value, expected in test_cases[base]: with matplotlib.rc_context({'text.usetex': False}): assert formatter(value) == expected diff --git a/lib/matplotlib/texmanager.py b/lib/matplotlib/texmanager.py index 99ab14ecc9a3..cb53e255a8c7 100644 --- a/lib/matplotlib/texmanager.py +++ b/lib/matplotlib/texmanager.py @@ -234,7 +234,7 @@ def get_basefile(self, tex, fontsize, dpi=None): def get_font_config(self): """Reinitializes self if relevant rcParams on have changed.""" if self._rc_cache is None: - self._rc_cache = dict([(k, None) for k in self._rc_cache_keys]) + self._rc_cache = dict.fromkeys(self._rc_cache_keys) changed = [par for par in self._rc_cache_keys if rcParams[par] != self._rc_cache[par]] if changed: diff --git a/lib/matplotlib/textpath.py b/lib/matplotlib/textpath.py index 2d73d2c82aac..54c389ad4047 100644 --- a/lib/matplotlib/textpath.py +++ b/lib/matplotlib/textpath.py @@ -49,7 +49,7 @@ def __init__(self): def _get_adobe_standard_encoding(self): enc_name = dviread.find_tex_file('8a.enc') enc = dviread.Encoding(enc_name) - return dict([(c, i) for i, c in enumerate(enc.encoding)]) + return {c: i for i, c in enumerate(enc.encoding)} def _get_font(self, prop): """ @@ -354,10 +354,10 @@ def get_glyphs_tex(self, prop, s, glyph_map=None, if charmap_name == "ADOBE_STANDARD" and font_bunch.encoding: enc0 = dviread.Encoding(font_bunch.encoding) - enc = dict([(i, self._adobe_standard_encoding.get(c, None)) - for i, c in enumerate(enc0.encoding)]) + enc = {i: self._adobe_standard_encoding.get(c, None) + for i, c in enumerate(enc0.encoding)} else: - enc = dict() + enc = {} self._ps_fontd[dvifont.texname] = font, enc else: diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index e55fdbfa2129..556b8ae761cc 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -952,7 +952,7 @@ def set_locs(self, locs=None): if numdec > self.minor_thresholds[0]: # Label only bases - self._sublabels = set((1,)) + self._sublabels = {1} elif numdec > self.minor_thresholds[1]: # Add labels between bases at log-spaced coefficients; # include base powers in case the locations include diff --git a/lib/mpl_toolkits/axes_grid1/parasite_axes.py b/lib/mpl_toolkits/axes_grid1/parasite_axes.py index a697e38d25bc..086806b182e3 100644 --- a/lib/mpl_toolkits/axes_grid1/parasite_axes.py +++ b/lib/mpl_toolkits/axes_grid1/parasite_axes.py @@ -26,8 +26,8 @@ class ParasiteAxesBase(object): def get_images_artists(self): - artists = set([a for a in self.get_children() if a.get_visible()]) - images = set([a for a in self.images if a.get_visible()]) + artists = {a for a in self.get_children() if a.get_visible()} + images = {a for a in self.images if a.get_visible()} return list(images), list(artists - images) diff --git a/lib/mpl_toolkits/gtktools.py b/lib/mpl_toolkits/gtktools.py index 3acc5c2ae000..f3e15d28cb4d 100644 --- a/lib/mpl_toolkits/gtktools.py +++ b/lib/mpl_toolkits/gtktools.py @@ -230,7 +230,6 @@ def clear(self): self.model.clear() self.datad = dict() - def flat(self, row): seq = [] for i,val in enumerate(row): @@ -239,9 +238,7 @@ def flat(self, row): return seq def __delete_selected(self, *unused): # untested - - - keyd = dict([(thisiter, key) for key, thisiter in self.iterd.values()]) + keyd = {thisiter: key for key, thisiter in self.iterd.values()} for row in self.get_selected(): key = tuple(row) thisiter = self.iterd[key] @@ -253,8 +250,6 @@ def __delete_selected(self, *unused): # untested for i, thisiter in enumerate(self.iters): self.rownumd[i] = keyd[thisiter] - - def delete_row(self, row): key = tuple(row) thisiter = self.iterd[key] diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 2b454232fa15..163441be9dbe 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -2599,7 +2599,7 @@ def calc_arrow(uvw, angle=15): # must all be ndarray assert all(isinstance(k, np.ndarray) for k in input_args) # must all in same shape - assert len(set([k.shape for k in input_args])) == 1 + assert len({k.shape for k in input_args}) == 1 shaft_dt = np.linspace(0, length, num=2) arrow_dt = shaft_dt * arrow_length_ratio From f1b25e6337a7c15b00561b19dbc5da6d3688e025 Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Thu, 1 Dec 2016 17:56:13 -0800 Subject: [PATCH 6/6] Minor fixes following comments. --- examples/pylab_examples/figimage_demo.py | 2 +- examples/pylab_examples/mri_with_eeg.py | 2 +- lib/matplotlib/backends/backend_pdf.py | 3 ++- lib/matplotlib/cbook.py | 14 ++++---------- lib/matplotlib/quiver.py | 2 +- lib/matplotlib/ticker.py | 5 +++-- 6 files changed, 12 insertions(+), 16 deletions(-) diff --git a/examples/pylab_examples/figimage_demo.py b/examples/pylab_examples/figimage_demo.py index d14d5ec282a0..ac077235bbc6 100644 --- a/examples/pylab_examples/figimage_demo.py +++ b/examples/pylab_examples/figimage_demo.py @@ -9,7 +9,7 @@ fig = plt.figure() -Z = np.arange(10000).reshape(100, 100) +Z = np.arange(10000).reshape((100, 100)) Z[:, 50:] = 1 im1 = fig.figimage(Z, xo=50, yo=0, origin='lower') diff --git a/examples/pylab_examples/mri_with_eeg.py b/examples/pylab_examples/mri_with_eeg.py index 433feb0b2c3c..fd97dec2dde8 100755 --- a/examples/pylab_examples/mri_with_eeg.py +++ b/examples/pylab_examples/mri_with_eeg.py @@ -16,7 +16,7 @@ # Load the MRI data (256x256 16 bit integers) dfile = cbook.get_sample_data('s1045.ima.gz') -im = np.fromstring(dfile.read(), np.uint16).astype(float).reshape((256, 256)) +im = np.fromstring(dfile.read(), np.uint16).reshape((256, 256)) dfile.close() # Plot the MRI image diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 797429a6a296..158a8ce1c2bf 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -560,7 +560,8 @@ def close(self): {val[0]: val[1] for val in six.itervalues(self.alphaStates)}) self.writeHatches() self.writeGouraudTriangles() - xobjects = dict(x[1:] for x in six.itervalues(self._images)) + xobjects = { + name: ob for image, name, ob in six.itervalues(self._images)} for tup in six.itervalues(self.markers): xobjects[tup[0]] = tup[1] for name, value in six.iteritems(self.multi_byte_charprocs): diff --git a/lib/matplotlib/cbook.py b/lib/matplotlib/cbook.py index 9939a3d55126..e12710960cbc 100644 --- a/lib/matplotlib/cbook.py +++ b/lib/matplotlib/cbook.py @@ -2067,16 +2067,10 @@ def unmasked_index_ranges(mask, compressed=True): ic1 = breakpoints return np.concatenate((ic0[:, np.newaxis], ic1[:, np.newaxis]), axis=1) -# a dict to cross-map linestyle arguments -_linestyles = [('-', 'solid'), - ('--', 'dashed'), - ('-.', 'dashdot'), - (':', 'dotted')] - -ls_mapper = dict(_linestyles) -# The ls_mapper maps short codes for line style to their full name used -# by backends -# The reverse mapper is for mapping full names to short ones + +# The ls_mapper maps short codes for line style to their full name used by +# backends; the reverse mapper is for mapping full names to short ones. +ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'} ls_mapper_r = reverse_dict(ls_mapper) diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py index fc6e3195c3bc..cf96843fbac3 100644 --- a/lib/matplotlib/quiver.py +++ b/lib/matplotlib/quiver.py @@ -657,7 +657,7 @@ def _make_verts(self, U, V): theta = np.angle(uv) else: theta = ma.masked_invalid(np.deg2rad(self.angles)).filled(0) - theta = theta.reshape((-1, 1)) # for broadcasting + theta = theta.reshape((-1, 1)) # for broadcasting xy = (X + Y * 1j) * np.exp(1j * theta) * self.width xy = xy[:, :, np.newaxis] XY = np.concatenate((xy.real, xy.imag), axis=2) diff --git a/lib/matplotlib/ticker.py b/lib/matplotlib/ticker.py index 556b8ae761cc..78da055b9834 100644 --- a/lib/matplotlib/ticker.py +++ b/lib/matplotlib/ticker.py @@ -1623,8 +1623,9 @@ def view_limits(self, vmin, vmax): vmax += 1 if rcParams['axes.autolimit_mode'] == 'round_numbers': - exponent = round(math.log10(vmax - vmin) - / math.log10(max(self.numticks - 1, 1))) - 1 + exponent, remainder = _divmod( + math.log10(vmax - vmin), math.log10(max(self.numticks - 1, 1))) + exponent -= (remainder < .5) scale = max(self.numticks - 1, 1) ** (-exponent) vmin = math.floor(scale * vmin) / scale vmax = math.ceil(scale * vmax) / scale 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