From 9b0af8ac06c553048dd3290bcf93012628401943 Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Tue, 24 Feb 2015 20:51:10 -0800 Subject: [PATCH 1/5] STY: Various pep8 fixes - specifically targeting travis pep8 failures --- .../pylab_examples/demo_annotation_box.py | 2 -- examples/pylab_examples/multipage_pdf.py | 4 +-- .../tricontour_smooth_delaunay.py | 25 ++++++++-------- examples/user_interfaces/embedding_in_tk.py | 5 ++-- lib/matplotlib/cm.py | 8 ++--- lib/matplotlib/colors.py | 30 +++++++++---------- lib/matplotlib/image.py | 29 ++++++++---------- 7 files changed, 49 insertions(+), 54 deletions(-) diff --git a/examples/pylab_examples/demo_annotation_box.py b/examples/pylab_examples/demo_annotation_box.py index 0bb5c5b81b5e..22a2b6956143 100644 --- a/examples/pylab_examples/demo_annotation_box.py +++ b/examples/pylab_examples/demo_annotation_box.py @@ -43,7 +43,6 @@ boxcoords=("axes fraction", "data"), box_alignment=(0., 0.5), arrowprops=dict(arrowstyle="->")) - #arrowprops=None) ax.add_artist(ab) @@ -56,7 +55,6 @@ boxcoords="offset points", pad=0.3, arrowprops=dict(arrowstyle="->")) - #arrowprops=None) ax.add_artist(ab) diff --git a/examples/pylab_examples/multipage_pdf.py b/examples/pylab_examples/multipage_pdf.py index c32b73bee3ec..07ab80ab1b2c 100644 --- a/examples/pylab_examples/multipage_pdf.py +++ b/examples/pylab_examples/multipage_pdf.py @@ -23,8 +23,8 @@ x = np.arange(0, 5, 0.1) plt.plot(x, np.sin(x), 'b-') plt.title('Page Two') - pdf.attach_note("plot of sin(x)") # you can add a pdf note to - # attach metadata to a page + # you can add a pdf note to attach metadata to a page + pdf.attach_note("plot of sin(x)") pdf.savefig() plt.close() diff --git a/examples/pylab_examples/tricontour_smooth_delaunay.py b/examples/pylab_examples/tricontour_smooth_delaunay.py index a155347dcb90..b485ffbcd1d3 100644 --- a/examples/pylab_examples/tricontour_smooth_delaunay.py +++ b/examples/pylab_examples/tricontour_smooth_delaunay.py @@ -45,18 +45,19 @@ def experiment_res(x, y): # User parameters for data test points n_test = 200 # Number of test data points, tested from 3 to 5000 for subdiv=3 -subdiv = 3 # Number of recursive subdivisions of the initial mesh for smooth - # plots. Values >3 might result in a very high number of triangles - # for the refine mesh: new triangles numbering = (4**subdiv)*ntri - -init_mask_frac = 0.0 # Float > 0. adjusting the proportion of - # (invalid) initial triangles which will be masked - # out. Enter 0 for no mask. - -min_circle_ratio = .01 # Minimum circle ratio - border triangles with circle - # ratio below this will be masked if they touch a - # border. Suggested value 0.01 ; Use -1 to keep - # all triangles. +# Number of recursive subdivisions of the initial mesh for smooth plots. +# Values >3 might result in a very high number of triangles for the refine +# mesh: new triangles numbering = (4**subdiv)*ntri +subdiv = 3 + +# Float > 0. adjusting the proportion of (invalid) initial triangles which will +# be masked out. Enter 0 for no mask. +init_mask_frac = 0.0 + +# Minimum circle ratio - border triangles with circle ratio below this will +# be masked if they touch a border. Suggested value 0.01; Use -1 to keep +# all triangles. +min_circle_ratio = .01 # Random points random_gen = np.random.mtrand.RandomState(seed=127260) diff --git a/examples/user_interfaces/embedding_in_tk.py b/examples/user_interfaces/embedding_in_tk.py index 4c93d25a9c84..6ff0ba13ebf8 100755 --- a/examples/user_interfaces/embedding_in_tk.py +++ b/examples/user_interfaces/embedding_in_tk.py @@ -48,8 +48,9 @@ def on_key_event(event): def _quit(): root.quit() # stops mainloop - root.destroy() # this is necessary on Windows to prevent - # Fatal Python Error: PyEval_RestoreThread: NULL tstate + # this is necessary on Windows to prevent + # Fatal Python Error: PyEval_RestoreThread: NULL tstate + root.destroy() button = Tk.Button(master=root, text='Quit', command=_quit) button.pack(side=Tk.BOTTOM) diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 27e56be8fb3f..9c3bc175632b 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -37,10 +37,10 @@ def revcmap(data): for key, val in six.iteritems(data): if six.callable(val): valnew = _reverser(val) - # This doesn't work: lambda x: val(1-x) - # The same "val" (the first one) is used - # each time, so the colors are identical - # and the result is shades of gray. + # This doesn't work: lambda x: val(1-x) + # The same "val" (the first one) is used + # each time, so the colors are identical + # and the result is shades of gray. else: # Flip x and exchange the y values facing x = 0 and x = 1. valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)] diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index adc2bffff79d..fbc5cdcafa9a 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -482,8 +482,8 @@ def makeMappingArray(N, data, gamma=1.0): lut[-1] = y0[-1] # ensure that the lut is confined to values between 0 and 1 by clipping it np.clip(lut, 0.0, 1.0) - #lut = where(lut > 1., 1., lut) - #lut = where(lut < 0., 0., lut) + # lut = where(lut > 1., 1., lut) + # lut = where(lut < 0., 0., lut) return lut @@ -614,9 +614,9 @@ def __call__(self, X, alpha=None, bytes=False): rgba = np.empty(shape=xa.shape + (4,), dtype=lut.dtype) lut.take(xa, axis=0, mode='clip', out=rgba) - # twice as fast as lut[xa]; - # using the clip or wrap mode and providing an - # output array speeds it up a little more. + # twice as fast as lut[xa]; + # using the clip or wrap mode and providing an + # output array speeds it up a little more. if vtype == 'scalar': rgba = tuple(rgba[0, :]) return rgba @@ -810,8 +810,8 @@ def __init__(self, colors, name='from_list', N=None): the list will be extended by repetition. """ self.colors = colors - self.monochrome = False # True only if all colors in map are - # identical; needed for contouring. + # True only if all colors in map are identical; needed for contouring. + self.monochrome = False if N is None: N = len(self.colors) else: @@ -1384,13 +1384,13 @@ def hsv_to_rgb(hsv): rgb : (..., 3) ndarray Colors converted to RGB values in range [0, 1] """ - # make sure it is an ndarray + # make sure it is an ndarray hsv = np.asarray(hsv) # check length of the last dimension, should be _some_ sort of rgb if hsv.shape[-1] != 3: raise ValueError("Last dimension of input array must be 3; " - "shape {shp} was found.".format(shp=hsv.shape)) + "shape {shp} was found.".format(shp=hsv.shape)) # if we got pased a 1D array, try to treat as # a single color and reshape as needed @@ -1551,20 +1551,20 @@ def hillshade(self, elevation, vert_exag=1, dx=1, dy=1, fraction=1.): # consistent to what `imshow` assumes, as well. dy = -dy - #-- Calculate the intensity from the illumination angle + # Calculate the intensity from the illumination angle dy, dx = np.gradient(vert_exag * elevation, dy, dx) # The aspect is defined by the _downhill_ direction, thus the negative aspect = np.arctan2(-dy, -dx) slope = 0.5 * np.pi - np.arctan(np.hypot(dx, dy)) - intensity = (np.sin(alt) * np.sin(slope) - + np.cos(alt) * np.cos(slope) - * np.cos(az - aspect)) + intensity = (np.sin(alt) * np.sin(slope) + + np.cos(alt) * np.cos(slope) * + np.cos(az - aspect)) - #-- Apply contrast stretch + # Apply contrast stretch imin, imax = intensity.min(), intensity.max() intensity *= fraction - #-- Rescale to 0-1, keeping range before contrast stretch + # Rescale to 0-1, keeping range before contrast stretch # If constant slope, keep relative scaling (i.e. flat should be 0.5, # fully occluded 0, etc.) if (imax - imin) > 1e-6: diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index d447d18703c4..0e3f633107d7 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -331,9 +331,10 @@ def _draw_unsampled_image(self, renderer, gc): if numrows <= 0 or numcols <= 0: return - im.resize(numcols, numrows) # just to create im.bufOut that - # is required by backends. There - # may be better solution -JJL + + # just to create im.bufOut that is required by backends. There may be + # a better solution -JJL + im.resize(numcols, numrows) im._url = self.get_url() im._gid = self.get_gid() @@ -353,7 +354,7 @@ def draw(self, renderer, *args, **kwargs): if not self.get_visible(): return if (self.axes.get_xscale() != 'linear' or - self.axes.get_yscale() != 'linear'): + self.axes.get_yscale() != 'linear'): warnings.warn("Images are not supported on non-linear axes.") l, b, widthDisplay, heightDisplay = self.axes.bbox.bounds @@ -392,7 +393,7 @@ def contains(self, mouseevent): xmin, xmax = xmax, xmin if ymin > ymax: ymin, ymax = ymax, ymin - #print x, y, xmin, xmax, ymin, ymax + if x is not None and y is not None: inside = ((x >= xmin) and (x <= xmax) and (y >= ymin) and (y <= ymax)) @@ -426,11 +427,11 @@ def set_data(self, A): self._A = cbook.safe_masked_invalid(A) if (self._A.dtype != np.uint8 and - not np.can_cast(self._A.dtype, np.float)): + not np.can_cast(self._A.dtype, np.float)): raise TypeError("Image data can not convert to float") if (self._A.ndim not in (2, 3) or - (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))): + (self._A.ndim == 3 and self._A.shape[-1] not in (3, 4))): raise TypeError("Invalid dimensions for image data") self._imcache = None @@ -677,7 +678,6 @@ def get_extent(self): return self._extent else: sz = self.get_size() - #print 'sz', sz numrows, numcols = sz if self.origin == 'upper': return (-0.5, numcols-0.5, numrows-0.5, -0.5) @@ -914,7 +914,7 @@ def set_data(self, x, y, A): if A.ndim == 3: if A.shape[2] in [3, 4]: if ((A[:, :, 0] == A[:, :, 1]).all() and - (A[:, :, 0] == A[:, :, 2]).all()): + (A[:, :, 0] == A[:, :, 2]).all()): self.is_grayscale = True else: raise ValueError("3D arrays must have RGB or RGBA as last dim") @@ -972,7 +972,7 @@ def contains(self, mouseevent): return self._contains(self, mouseevent) xmin, xmax, ymin, ymax = self.get_extent() xdata, ydata = mouseevent.x, mouseevent.y - #print xdata, ydata, xmin, xmax, ymin, ymax + if xdata is not None and ydata is not None: inside = ((xdata >= xmin) and (xdata <= xmax) and (ydata >= ymin) and (ydata <= ymax)) @@ -1014,7 +1014,6 @@ def make_image(self, magnification=1.0): self.magnification = magnification # if magnification is not one, we need to resize ismag = magnification != 1 - #if ismag: raise RuntimeError if ismag: isoutput = 0 else: @@ -1170,16 +1169,13 @@ def make_image(self, renderer, magnification=1.0): numrows, numcols = self._A.shape[:2] if (not self.interp_at_native and - widthDisplay == numcols and heightDisplay == numrows): + widthDisplay == numcols and heightDisplay == numrows): im.set_interpolation(0) # resize viewport to display rx = widthDisplay / numcols ry = heightDisplay / numrows - #im.apply_scaling(rx*sx, ry*sy) im.apply_scaling(rx, ry) - #im.resize(int(widthDisplay+0.5), int(heightDisplay+0.5), - # norm=self._filternorm, radius=self._filterrad) im.resize(int(widthDisplay), int(heightDisplay), norm=self._filternorm, radius=self._filterrad) return im @@ -1195,7 +1191,6 @@ def draw(self, renderer, *args, **kwargs): gc = renderer.new_gc() self._set_gc_clip(gc) gc.set_alpha(self.get_alpha()) - #gc.set_clip_path(self.get_clip_path()) l = np.min([x0, x1]) b = np.min([y0, y1]) @@ -1341,7 +1336,7 @@ def toarray(im, dtype=np.uint8): x.shape = im.size[1], im.size[0] return x elif pilImage.mode == 'RGB': - #return MxNx3 RGB array + # return MxNx3 RGB array im = pilImage # no need to RGB images x = toarray(im) x.shape = im.size[1], im.size[0], 3 From b52a8b12aceec3a9749d054dff7d6ef439150080 Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Tue, 24 Feb 2015 21:27:21 -0800 Subject: [PATCH 2/5] STY: More pep8 fixes --- lib/matplotlib/axes/_axes.py | 28 +++---- lib/matplotlib/axes/_base.py | 62 ++++++---------- lib/matplotlib/contour.py | 13 +--- lib/matplotlib/patches.py | 129 ++++++++++++++++----------------- lib/matplotlib/quiver.py | 40 +++++----- lib/matplotlib/sankey.py | 28 +++---- lib/matplotlib/tight_layout.py | 11 +-- 7 files changed, 141 insertions(+), 170 deletions(-) diff --git a/lib/matplotlib/axes/_axes.py b/lib/matplotlib/axes/_axes.py index c141627e2a7d..94cda34a29d0 100644 --- a/lib/matplotlib/axes/_axes.py +++ b/lib/matplotlib/axes/_axes.py @@ -2807,7 +2807,7 @@ def xywhere(xs, ys, mask): if yerr is not None: if (iterable(yerr) and len(yerr) == 2 and - iterable(yerr[0]) and iterable(yerr[1])): + iterable(yerr[0]) and iterable(yerr[1])): # using list comps rather than arrays to preserve units lower = [thisy - thiserr for (thisy, thiserr) in cbook.safezip(y, yerr[0])] @@ -3066,8 +3066,7 @@ def boxplot(self, x, notch=False, sym=None, vert=True, whis=1.5, # compatibility if sym == '': # blow away existing dict and make one for invisible markers - flierprops = dict(linestyle='none', marker='', - color='none') + flierprops = dict(linestyle='none', marker='', color='none') # turn the fliers off just to be safe showfliers = False # now process the symbol string @@ -3088,7 +3087,7 @@ def boxplot(self, x, notch=False, sym=None, vert=True, whis=1.5, # replace medians if necessary: if usermedians is not None: if (len(np.ravel(usermedians)) != len(bxpstats) or - np.shape(usermedians)[0] != len(bxpstats)): + np.shape(usermedians)[0] != len(bxpstats)): medmsg = 'usermedians length not compatible with x' raise ValueError(medmsg) else: @@ -4680,8 +4679,8 @@ def imshow(self, X, cmap=None, norm=None, aspect=None, aspect = rcParams['image.aspect'] self.set_aspect(aspect) im = mimage.AxesImage(self, cmap, norm, interpolation, origin, extent, - filternorm=filternorm, - filterrad=filterrad, resample=resample, **kwargs) + filternorm=filternorm, filterrad=filterrad, + resample=resample, **kwargs) im.set_data(X) im.set_alpha(alpha) @@ -4966,7 +4965,7 @@ def pcolor(self, *args, **kwargs): X3[:, newaxis], Y3[:, newaxis], X4[:, newaxis], Y4[:, newaxis], X1[:, newaxis], Y1[:, newaxis]), - axis=1) + axis=1) verts = xy.reshape((npoly, 5, 2)) C = compress(ravelmask, ma.filled(C[0:Ny - 1, 0:Nx - 1]).ravel()) @@ -4992,7 +4991,7 @@ def pcolor(self, *args, **kwargs): if 'antialiased' in kwargs: kwargs['antialiaseds'] = kwargs.pop('antialiased') if 'antialiaseds' not in kwargs and (is_string_like(ec) and - ec.lower() == "none"): + ec.lower() == "none"): kwargs['antialiaseds'] = False kwargs.setdefault('snap', False) @@ -5014,8 +5013,8 @@ def pcolor(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform - if (not isinstance(t, mtransforms.Transform) - and hasattr(t, '_as_mpl_transform')): + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -5161,8 +5160,8 @@ def pcolormesh(self, *args, **kwargs): # Transform from native to data coordinates? t = collection._transform - if (not isinstance(t, mtransforms.Transform) - and hasattr(t, '_as_mpl_transform')): + if (not isinstance(t, mtransforms.Transform) and + hasattr(t, '_as_mpl_transform')): t = t._as_mpl_transform(self.axes) if t and any(t.contains_branch_seperately(self.transData)): @@ -5310,8 +5309,9 @@ def pcolorfast(self, *args, **kwargs): # convert to one dimensional arrays # This should also be moved to the QuadMesh class - C = ma.ravel(C) # data point in each cell is value - # at lower left corner + + # data point in each cell is value at lower left corner + C = ma.ravel(C) X = x.ravel() Y = y.ravel() Nx = nc + 1 diff --git a/lib/matplotlib/axes/_base.py b/lib/matplotlib/axes/_base.py index ca635275aa31..c8e5b3cbb955 100644 --- a/lib/matplotlib/axes/_base.py +++ b/lib/matplotlib/axes/_base.py @@ -906,8 +906,10 @@ def cla(self): self.containers = [] self.grid(self._gridOn, which=rcParams['axes.grid.which']) - props = font_manager.FontProperties(size=rcParams['axes.titlesize'], - weight=rcParams['axes.titleweight']) + props = font_manager.FontProperties( + size=rcParams['axes.titlesize'], + weight=rcParams['axes.titleweight'] + ) self.titleOffsetTrans = mtransforms.ScaledTranslation( 0.0, 5.0 / 72.0, self.figure.dpi_scale_trans) @@ -1179,7 +1181,7 @@ def apply_aspect(self, position=None): else: A = aspect - #Ensure at drawing time that any Axes involved in axis-sharing + # Ensure at drawing time that any Axes involved in axis-sharing # does not have its position changed. if self in self._shared_x_axes or self in self._shared_y_axes: if self._adjustable == 'box': @@ -1218,10 +1220,8 @@ def apply_aspect(self, position=None): data_ratio = box_aspect / A y_expander = (data_ratio * xsize / ysize - 1.0) - #print 'y_expander', y_expander # If y_expander > 0, the dy/dx viewLim ratio needs to increase if abs(y_expander) < 0.005: - #print 'good enough already' return if aspect_scale_mode == "log": @@ -1241,16 +1241,13 @@ def apply_aspect(self, position=None): Xsize = ysize / data_ratio Xmarg = Xsize - xr Ymarg = Ysize - yr - xm = 0 # Setting these targets to, e.g., 0.05*xr does not seem to - # help. + xm = 0 # Setting these targets to, e.g., 0.05*xr does not seem to help ym = 0 - #print 'xmin, xmax, ymin, ymax', xmin, xmax, ymin, ymax - #print 'xsize, Xsize, ysize, Ysize', xsize, Xsize, ysize, Ysize - changex = (self in self._shared_y_axes - and self not in self._shared_x_axes) - changey = (self in self._shared_x_axes - and self not in self._shared_y_axes) + changex = (self in self._shared_y_axes and + self not in self._shared_x_axes) + changey = (self in self._shared_x_axes and + self not in self._shared_y_axes) if changex and changey: warnings.warn("adjustable='datalim' cannot work with shared " "x and y axes") @@ -1258,13 +1255,11 @@ def apply_aspect(self, position=None): if changex: adjust_y = False else: - #print 'xmarg, ymarg, Xmarg, Ymarg', xmarg, ymarg, Xmarg, Ymarg if xmarg > xm and ymarg > ym: - adjy = ((Ymarg > 0 and y_expander < 0) - or (Xmarg < 0 and y_expander > 0)) + adjy = ((Ymarg > 0 and y_expander < 0) or + (Xmarg < 0 and y_expander > 0)) else: adjy = y_expander > 0 - #print 'y_expander, adjy', y_expander, adjy adjust_y = changey or adjy # (Ymarg > xmarg) if adjust_y: yc = 0.5 * (ymin + ymax) @@ -1274,8 +1269,6 @@ def apply_aspect(self, position=None): self.set_ybound((10. ** y0, 10. ** y1)) else: self.set_ybound((y0, y1)) - #print 'New y0, y1:', y0, y1 - #print 'New ysize, ysize/xsize', y1-y0, (y1-y0)/xsize else: xc = 0.5 * (xmin + xmax) x0 = xc - Xsize / 2.0 @@ -1284,8 +1277,6 @@ def apply_aspect(self, position=None): self.set_xbound((10. ** x0, 10. ** x1)) else: self.set_xbound((x0, x1)) - #print 'New x0, x1:', x0, x1 - #print 'New xsize, ysize/xsize', x1-x0, ysize/(x1-x0) def axis(self, *v, **kwargs): """ @@ -1402,7 +1393,7 @@ def get_yticklines(self): return cbook.silent_list('Line2D ytickline', self.yaxis.get_ticklines()) - #### Adding and tracking artists + # Adding and tracking artists def _sci(self, im): """ @@ -1588,7 +1579,7 @@ def _update_patch_limits(self, patch): xys = patch.get_patch_transform().transform(vertices) if patch.get_data_transform() != self.transData: patch_to_data = (patch.get_data_transform() - - self.transData) + self.transData) xys = patch_to_data.transform(xys) updatex, updatey = patch.get_transform().\ @@ -1689,18 +1680,15 @@ def _process_unit_info(self, xdata=None, ydata=None, kwargs=None): if self.xaxis is None or self.yaxis is None: return - #print 'processing', self.get_geometry() if xdata is not None: # we only need to update if there is nothing set yet. if not self.xaxis.have_units(): self.xaxis.update_units(xdata) - #print '\tset from xdata', self.xaxis.units if ydata is not None: # we only need to update if there is nothing set yet. if not self.yaxis.have_units(): self.yaxis.update_units(ydata) - #print '\tset from ydata', self.yaxis.units # process kwargs 2nd since these will override default units if kwargs is not None: @@ -1708,7 +1696,6 @@ def _process_unit_info(self, xdata=None, ydata=None, kwargs=None): if self.name == 'polar': xunits = kwargs.pop('thetaunits', xunits) if xunits != self.xaxis.units: - #print '\tkw setting xunits', xunits self.xaxis.set_units(xunits) # If the units being set imply a different converter, # we need to update. @@ -1719,7 +1706,6 @@ def _process_unit_info(self, xdata=None, ydata=None, kwargs=None): if self.name == 'polar': yunits = kwargs.pop('runits', yunits) if yunits != self.yaxis.units: - #print '\tkw setting yunits', yunits self.yaxis.set_units(yunits) # If the units being set imply a different converter, # we need to update. @@ -1937,7 +1923,7 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True): if scalex and self._autoscaleXon: xshared = self._shared_x_axes.get_siblings(self) dl = [ax.dataLim for ax in xshared] - #ignore non-finite data limits if good limits exist + # ignore non-finite data limits if good limits exist finite_dl = [d for d in dl if np.isfinite(d).all()] if len(finite_dl): dl = finite_dl @@ -1963,7 +1949,7 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True): if scaley and self._autoscaleYon: yshared = self._shared_y_axes.get_siblings(self) dl = [ax.dataLim for ax in yshared] - #ignore non-finite data limits if good limits exist + # ignore non-finite data limits if good limits exist finite_dl = [d for d in dl if np.isfinite(d).all()] if len(finite_dl): dl = finite_dl @@ -1984,7 +1970,7 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True): y0, y1 = ylocator.view_limits(y0, y1) self.set_ybound(y0, y1) - #### Drawing + # Drawing @allow_rasterization def draw(self, renderer=None, inframe=False): @@ -2056,7 +2042,7 @@ def draw(self, renderer=None, inframe=False): # if the minimum zorder is negative, start rasterization rasterization_zorder = self._rasterization_zorder if (rasterization_zorder is not None and - len(dsu) > 0 and dsu[0][0] < rasterization_zorder): + len(dsu) > 0 and dsu[0][0] < rasterization_zorder): renderer.start_rasterizing() dsu_rasterized = [l for l in dsu if l[0] < rasterization_zorder] dsu = [l for l in dsu if l[0] >= rasterization_zorder] @@ -2133,7 +2119,7 @@ def redraw_in_frame(self): def get_renderer_cache(self): return self._cachedRenderer - #### Axes rectangle characteristics + # Axes rectangle characteristics def get_frame_on(self): """ @@ -2430,7 +2416,7 @@ def set_axis_bgcolor(self, color): self._axisbg = color self.patch.set_facecolor(color) - ### data limits, ticks, tick labels, and formatting + # data limits, ticks, tick labels, and formatting def invert_xaxis(self): "Invert the x-axis." @@ -2575,7 +2561,7 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw): other.set_xlim(self.viewLim.intervalx, emit=False, auto=auto) if (other.figure != self.figure and - other.figure.canvas is not None): + other.figure.canvas is not None): other.figure.canvas.draw_idle() return left, right @@ -2910,8 +2896,8 @@ def get_yticklabels(self, minor=False, which=None): List of :class:`~matplotlib.text.Text` instances. """ return cbook.silent_list('Text yticklabel', - self.yaxis.get_ticklabels(minor=minor, - which=which)) + self.yaxis.get_ticklabels(minor=minor, + which=which)) @docstring.dedent_interpd def set_yticklabels(self, labels, fontdict=None, minor=False, **kwargs): @@ -3004,7 +2990,7 @@ def minorticks_off(self): self.xaxis.set_minor_locator(mticker.NullLocator()) self.yaxis.set_minor_locator(mticker.NullLocator()) - #### Interactive manipulation + # Interactive manipulation def can_zoom(self): """ diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index c4b3d16de2fd..5eb67a1ba446 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -205,8 +205,6 @@ def clabel(self, *args, **kwargs): self.labelMappable = cm.ScalarMappable(cmap=cmap, norm=colors.NoNorm()) - #self.labelTexts = [] # Initialized in ContourSet.__init__ - #self.labelCValues = [] # same self.labelXYs = [] if cbook.iterable(self.labelManual): @@ -372,7 +370,7 @@ def locate_label(self, linecontour, labelwidth): XX = np.resize(linecontour[:, 0], (xsize, ysize)) YY = np.resize(linecontour[:, 1], (xsize, ysize)) - #I might have fouled up the following: + # I might have fouled up the following: yfirst = YY[:, 0].reshape(xsize, 1) ylast = YY[:, -1].reshape(xsize, 1) xfirst = XX[:, 0].reshape(xsize, 1) @@ -381,13 +379,10 @@ def locate_label(self, linecontour, labelwidth): L = np.sqrt((xlast - xfirst) ** 2 + (ylast - yfirst) ** 2).ravel() dist = np.add.reduce(([(abs(s)[i] / L[i]) for i in range(xsize)]), -1) x, y, ind = self.get_label_coords(dist, XX, YY, ysize, labelwidth) - #print 'ind, x, y', ind, x, y # There must be a more efficient way... lc = [tuple(l) for l in linecontour] dind = lc.index((x, y)) - #print 'dind', dind - #dind = list(linecontour).index((x,y)) return x, y, dind @@ -494,7 +489,7 @@ def calc_label_rot_and_inline(self, slc, ind, lw, lc=None, spacing=5): # The current implementation removes contours completely # covered by labels. Uncomment line below to keep # original contour if this is the preferred behavior. - #if not len(nlc): nlc = [ lc ] + # if not len(nlc): nlc = [ lc ] return rotation, nlc @@ -843,8 +838,8 @@ def __init__(self, ax, *args, **kwargs): self.extend = kwargs.get('extend', 'neither') self.antialiased = kwargs.get('antialiased', None) if self.antialiased is None and self.filled: - self.antialiased = False # eliminate artifacts; we are not - # stroking the boundaries. + # eliminate artifacts; we are not stroking the boundaries + self.antialiased = False # The default for line contours will be taken from # the LineCollection default, which uses the # rcParams['lines.antialiased'] diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 5becac92a9d0..860cc16f2107 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -102,8 +102,7 @@ def __init__(self, self._fill = True # needed for set_facecolor call if color is not None: - if (edgecolor is not None or - facecolor is not None): + if (edgecolor is not None or facecolor is not None): import warnings warnings.warn("Setting the 'color' property will override" "the edgecolor or facecolor properties. ") @@ -286,8 +285,8 @@ def set_facecolor(self, color): """ if color is None: color = mpl.rcParams['patch.facecolor'] - self._original_facecolor = color # save: otherwise changing _fill - # may lose alpha information + # save: otherwise changing _fill may lose alpha information + self._original_facecolor = color self._facecolor = colors.colorConverter.to_rgba(color, self._alpha) if not self._fill: self._facecolor = list(self._facecolor) @@ -323,8 +322,8 @@ def set_alpha(self, alpha): except TypeError: raise TypeError('alpha must be a float or None') artist.Artist.set_alpha(self, alpha) - self.set_facecolor(self._original_facecolor) # using self._fill and - # self._alpha + # using self._fill and self._alpha + self.set_facecolor(self._original_facecolor) self.set_edgecolor(self._original_edgecolor) def set_linewidth(self, w): @@ -381,8 +380,8 @@ def set_capstyle(self, s): """ s = s.lower() if s not in self.validCap: - raise ValueError('set_capstyle passed "%s";\n' % (s,) - + 'valid capstyles are %s' % (self.validCap,)) + raise ValueError('set_capstyle passed "%s";\n' % (s,) + + 'valid capstyles are %s' % (self.validCap,)) self._capstyle = s def get_capstyle(self): @@ -397,8 +396,8 @@ def set_joinstyle(self, s): """ s = s.lower() if s not in self.validJoin: - raise ValueError('set_joinstyle passed "%s";\n' % (s,) - + 'valid joinstyles are %s' % (self.validJoin,)) + raise ValueError('set_joinstyle passed "%s";\n' % (s,) + + 'valid joinstyles are %s' % (self.validJoin,)) self._joinstyle = s def get_joinstyle(self): @@ -1076,8 +1075,8 @@ def __str__(self): @docstring.dedent_interpd def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, - head_width=None, head_length=None, shape='full', overhang=0, - head_starts_at_zero=False, **kwargs): + head_width=None, head_length=None, shape='full', overhang=0, + head_starts_at_zero=False, **kwargs): """ Constructor arguments *width*: float (default: 0.001) @@ -1123,19 +1122,19 @@ def __init__(self, x, y, dx, dy, width=0.001, length_includes_head=False, # start by drawing horizontal arrow, point at (0,0) hw, hl, hs, lw = head_width, head_length, overhang, width left_half_arrow = np.array([ - [0.0, 0.0], # tip + [0.0, 0.0], # tip [-hl, -hw / 2.0], # leftmost [-hl * (1 - hs), -lw / 2.0], # meets stem [-length, -lw / 2.0], # bottom left [-length, 0], ]) - #if we're not including the head, shift up by head length + # if we're not including the head, shift up by head length if not length_includes_head: left_half_arrow += [head_length, 0] - #if the head starts at 0, shift up by another head length + # if the head starts at 0, shift up by another head length if head_starts_at_zero: left_half_arrow += [head_length / 2.0, 0] - #figure out the shape, and complete accordingly + # figure out the shape, and complete accordingly if shape == 'left': coords = left_half_arrow else: @@ -1517,7 +1516,7 @@ def draw(self, renderer): inv_error = (1.0 / 1.89818e-6) * 0.5 if width < inv_error and height < inv_error: - #self._path = Path.arc(self.theta1, self.theta2) + # self._path = Path.arc(self.theta1, self.theta2) return Patch.draw(self, renderer) def iter_circle_intersect_on_line(x0, y0, x1, y1): @@ -1641,7 +1640,7 @@ def bbox_artist(artist, renderer, props=None, fill=True): width=w, height=h, fill=fill, - ) + ) r.set_transform(transforms.IdentityTransform()) r.set_clip_on(False) r.update(props) @@ -1662,7 +1661,7 @@ def draw_bbox(bbox, renderer, color='k', trans=None): height=h, edgecolor=color, fill=False, - ) + ) if trans is not None: r.set_transform(trans) r.set_clip_on(False) @@ -1733,7 +1732,7 @@ def _pprint_styles(_styles): for an, av in args]) - #adding ``quotes`` since - and | have special meaning in reST + # adding ``quotes`` since - and | have special meaning in reST _table.append([cls.__name__, "``%s``" % name, argstr]) return _pprint_table(_table) @@ -1975,8 +1974,7 @@ def transmute(self, x0, y0, width, height, mutation_size): pad = mutation_size * self.pad # width and height with padding added. - width, height = width + 2. * pad, \ - height + 2. * pad, + width, height = width + 2. * pad, height + 2. * pad # boundary of the padded box x0, y0 = x0 - pad, y0 - pad, @@ -2007,7 +2005,6 @@ class RArrow(LArrow): """ def __init__(self, pad=0.3): - #self.pad = pad super(BoxStyle.RArrow, self).__init__(pad) def transmute(self, x0, y0, width, height, mutation_size): @@ -2100,8 +2097,7 @@ def transmute(self, x0, y0, width, height, mutation_size): else: dr = pad - width, height = width + 2. * pad, \ - height + 2. * pad, + width, height = width + 2. * pad, height + 2. * pad x0, y0 = x0 - pad, y0 - pad, x1, y1 = x0 + width, y0 + height @@ -2165,8 +2161,8 @@ def transmute(self, x0, y0, width, height, mutation_size): else: dr = pad / 2. - width, height = width + 2. * pad - 2 * dr, \ - height + 2. * pad - 2 * dr, + width, height = (width + 2. * pad - 2 * dr, + height + 2. * pad - 2 * dr) x0, y0 = x0 - pad + dr, y0 - pad + dr, x1, y1 = x0 + width, y0 + height @@ -2220,8 +2216,8 @@ def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size): tooth_size = self.tooth_size * mutation_size tooth_size2 = tooth_size / 2. - width, height = width + 2. * pad - tooth_size, \ - height + 2. * pad - tooth_size, + width, height = (width + 2. * pad - tooth_size, + height + 2. * pad - tooth_size) # the sizes of the vertical and horizontal sawtooth are # separately adjusted to fit the given box size. @@ -2283,11 +2279,11 @@ def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size): in range(dsy_n * 2)] + \ [y0 + tooth_size2] - saw_vertices = list(zip(bottom_saw_x, bottom_saw_y)) + \ - list(zip(right_saw_x, right_saw_y)) + \ - list(zip(top_saw_x, top_saw_y)) + \ - list(zip(left_saw_x, left_saw_y)) + \ - [(bottom_saw_x[0], bottom_saw_y[0])] + saw_vertices = (list(zip(bottom_saw_x, bottom_saw_y)) + + list(zip(right_saw_x, right_saw_y)) + + list(zip(top_saw_x, top_saw_y)) + + list(zip(left_saw_x, left_saw_y)) + + [(bottom_saw_x[0], bottom_saw_y[0])]) return saw_vertices @@ -2320,8 +2316,8 @@ def transmute(self, x0, y0, width, height, mutation_size): saw_vertices = np.concatenate([np.array(saw_vertices), [saw_vertices[0]]], axis=0) codes = ([Path.MOVETO] + - [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1) // 2) + - [Path.CLOSEPOLY]) + [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1) // 2) + + [Path.CLOSEPOLY]) return Path(saw_vertices, codes) _style_list["roundtooth"] = Roundtooth @@ -2750,10 +2746,10 @@ def connect(self, posA, posB): x1, y1 = posA x2, y2 = posB - cosA, sinA = math.cos(self.angleA / 180. * math.pi),\ - math.sin(self.angleA / 180. * math.pi), - cosB, sinB = math.cos(self.angleB / 180. * math.pi),\ - math.sin(self.angleB / 180. * math.pi), + cosA, sinA = (math.cos(self.angleA / 180. * math.pi), + math.sin(self.angleA / 180. * math.pi)) + cosB, sinB = (math.cos(self.angleB / 180. * math.pi), + math.sin(self.angleB / 180. * math.pi)) cx, cy = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) @@ -2795,10 +2791,10 @@ def connect(self, posA, posB): x1, y1 = posA x2, y2 = posB - cosA, sinA = math.cos(self.angleA / 180. * math.pi),\ - math.sin(self.angleA / 180. * math.pi), - cosB, sinB = math.cos(self.angleB / 180. * math.pi),\ - math.sin(self.angleB / 180. * math.pi), + cosA, sinA = (math.cos(self.angleA / 180. * math.pi), + math.sin(self.angleA / 180. * math.pi)) + cosB, sinB = (math.cos(self.angleB / 180. * math.pi), + math.sin(self.angleB / 180. * math.pi)) cx, cy = get_intersection(x1, y1, cosA, sinA, x2, y2, cosB, sinB) @@ -2873,7 +2869,7 @@ def connect(self, posA, posB): if self.armA: cosA = math.cos(self.angleA / 180. * math.pi) sinA = math.sin(self.angleA / 180. * math.pi) - #x_armA, y_armB + # x_armA, y_armB d = self.armA - self.rad rounded.append((x1 + d * cosA, y1 + d * sinA)) d = self.armA @@ -3182,8 +3178,7 @@ def __init__(self, beginarrow=None, endarrow=None, fillend) is True. """ self.beginarrow, self.endarrow = beginarrow, endarrow - self.head_length, self.head_width = \ - head_length, head_width + self.head_length, self.head_width = head_length, head_width self.fillbegin, self.fillend = fillbegin, fillend super(ArrowStyle._Curve, self).__init__() @@ -3432,8 +3427,7 @@ def __init__(self, bracketA=None, bracketB=None, widthA=1., widthB=1., lengthA=0.2, lengthB=0.2, angleA=None, angleB=None, - scaleA=None, scaleB=None - ): + scaleA=None, scaleB=None): self.bracketA, self.bracketB = bracketA, bracketB self.widthA, self.widthB = widthA, widthB self.lengthA, self.lengthB = lengthA, lengthB @@ -3441,8 +3435,7 @@ def __init__(self, bracketA=None, bracketB=None, self.scaleA, self.scaleB = scaleA, scaleB def _get_bracket(self, x0, y0, - cos_t, sin_t, width, length, - ): + cos_t, sin_t, width, length): # arrow from x0, y0 to x1, y1 from matplotlib.bezier import get_normal_points @@ -3558,7 +3551,9 @@ def __init__(self, widthA=1., lengthA=0.2, angleA=None): """ super(ArrowStyle.BracketA, self).__init__(True, None, - widthA=widthA, lengthA=lengthA, angleA=angleA) + widthA=widthA, + lengthA=lengthA, + angleA=angleA) _style_list["]-"] = BracketA @@ -3580,7 +3575,9 @@ def __init__(self, widthB=1., lengthB=0.2, angleB=None): """ super(ArrowStyle.BracketB, self).__init__(None, True, - widthB=widthB, lengthB=lengthB, angleB=angleB) + widthB=widthB, + lengthB=lengthB, + angleB=angleB) _style_list["-["] = BracketB @@ -3637,7 +3634,7 @@ def __init__(self, head_length=.5, head_width=.5, tail_width=.2): """ self.head_length, self.head_width, self.tail_width = \ - head_length, head_width, tail_width + head_length, head_width, tail_width super(ArrowStyle.Simple, self).__init__() def transmute(self, path, mutation_size, linewidth): @@ -3666,9 +3663,8 @@ def transmute(self, path, mutation_size, linewidth): # head head_width = self.head_width * mutation_size - head_left, head_right = \ - make_wedged_bezier2(arrow_in, head_width / 2., - wm=.5) + head_left, head_right = make_wedged_bezier2(arrow_in, + head_width / 2., wm=.5) # tail if arrow_out is not None: @@ -3676,7 +3672,6 @@ def transmute(self, path, mutation_size, linewidth): tail_left, tail_right = get_parallels(arrow_out, tail_width / 2.) - #head_right, head_left = head_r, head_l patch_path = [(Path.MOVETO, tail_right[0]), (Path.CURVE3, tail_right[1]), (Path.CURVE3, tail_right[2]), @@ -3725,7 +3720,7 @@ def __init__(self, head_length=.4, head_width=.4, tail_width=.4): """ self.head_length, self.head_width, self.tail_width = \ - head_length, head_width, tail_width + head_length, head_width, tail_width super(ArrowStyle.Fancy, self).__init__() def transmute(self, path, mutation_size, linewidth): @@ -3758,11 +3753,11 @@ def transmute(self, path, mutation_size, linewidth): # path for head in_f = inside_circle(x2, y2, head_length * .8) - path_out, path_in = \ - split_bezier_intersecting_with_closedpath( + path_out, path_in = split_bezier_intersecting_with_closedpath( arrow_path, in_f, - tolerence=0.01) + tolerence=0.01 + ) path_tail = path_out # head @@ -3779,11 +3774,11 @@ def transmute(self, path, mutation_size, linewidth): # path for head in_f = inside_circle(x0, y0, tail_width * .3) - path_in, path_out = \ - split_bezier_intersecting_with_closedpath( - arrow_path, - in_f, - tolerence=0.01) + path_in, path_out = split_bezier_intersecting_with_closedpath( + arrow_path, + in_f, + tolerence=0.01 + ) tail_start = path_in[-1] head_right, head_left = head_r, head_l diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py index 3a2fdcc2fdfc..f547329687d1 100644 --- a/lib/matplotlib/quiver.py +++ b/lib/matplotlib/quiver.py @@ -249,10 +249,9 @@ def on_dpi_change(fig): self_weakref = weak_self() if self_weakref is not None: self_weakref.labelsep = (self_weakref._labelsep_inches*fig.dpi) - self_weakref._initialized = False # simple brute force update - # works because _init is - # called at the start of - # draw. + # simple brute force update works because _init is called at + # the start of draw + self_weakref._initialized = False self._cid = Q.ax.figure.callbacks.connect('dpi_changed', on_dpi_change) @@ -356,8 +355,8 @@ def set_figure(self, fig): def contains(self, mouseevent): # Maybe the dictionary should allow one to # distinguish between a text hit and a vector hit. - if (self.text.contains(mouseevent)[0] - or self.vector.contains(mouseevent)[0]): + if (self.text.contains(mouseevent)[0] or + self.vector.contains(mouseevent)[0]): return True, {} return False, {} @@ -452,9 +451,9 @@ def __init__(self, ax, *args, **kw): kw.setdefault('facecolors', self.color) kw.setdefault('linewidths', (0,)) mcollections.PolyCollection.__init__(self, [], offsets=self.XY, - transOffset=self.transform, - closed=False, - **kw) + transOffset=self.transform, + closed=False, + **kw) self.polykw = kw self.set_UVC(U, V, C) self._initialized = False @@ -468,12 +467,11 @@ def __init__(self, ax, *args, **kw): def on_dpi_change(fig): self_weakref = weak_self() if self_weakref is not None: - self_weakref._new_UV = True # vertices depend on width, span - # which in turn depend on dpi - self_weakref._initialized = False # simple brute force update - # works because _init is - # called at the start of - # draw. + # vertices depend on width, span which in turn depend on dpi + self_weakref._new_UV = True + # simple brute force update works because _init is called at + # the start of draw + self_weakref._initialized = False self._cid = self.ax.figure.callbacks.connect('dpi_changed', on_dpi_change) @@ -622,9 +620,9 @@ def _make_verts(self, U, V): amean = a[~self.Umask].mean() else: amean = a.mean() - scale = 1.8 * amean * sn / self.span # crude auto-scaling - # scale is typical arrow length as a multiple - # of the arrow width + # crude auto-scaling + # scale is typical arrow length as a multiple of the arrow width + scale = 1.8 * amean * sn / self.span if self.scale_units is None: if self.scale is None: self.scale = scale @@ -700,9 +698,9 @@ def _h_arrows(self, length): if self.pivot == 'middle': X -= 0.5 * X[:, 3, np.newaxis] elif self.pivot == 'tip': - X = X - X[:, 3, np.newaxis] # numpy bug? using -= does not - # work here unless we multiply - # by a float first, as with 'mid'. + # numpy bug? using -= does not work here unless we multiply by a + # float first, as with 'mid'. + X = X - X[:, 3, np.newaxis] tooshort = length < self.minlength if tooshort.any(): # Use a heptagonal dot: diff --git a/lib/matplotlib/sankey.py b/lib/matplotlib/sankey.py index a78ac20464fd..b5f8e735e066 100755 --- a/lib/matplotlib/sankey.py +++ b/lib/matplotlib/sankey.py @@ -225,7 +225,7 @@ def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)): [5.19642327e-01, 8.94571235e-01], [2.65114773e-01, 1.00000000e+00], # Insignificant - #[6.12303177e-17, 1.00000000e+00]]) + # [6.12303177e-17, 1.00000000e+00]]) [0.00000000e+00, 1.00000000e+00]]) if quadrant == 0 or quadrant == 2: if cw: @@ -369,10 +369,10 @@ def _revert(self, path, first_action=Path.LINETO): return reverse_path # This might be more efficient, but it fails because 'tuple' object # doesn't support item assignment: - #path[1] = path[1][-1:0:-1] - #path[1][0] = first_action - #path[2] = path[2][::-1] - #return path + # path[1] = path[1][-1:0:-1] + # path[1][0] = first_action + # path[2] = path[2][::-1] + # return path @docstring.dedent_interpd def add(self, patchlabel='', flows=None, orientations=None, labels='', @@ -475,8 +475,8 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', "orientations has length %d, but flows has length %d." % (len(orientations), n)) if labels != '' and getattr(labels, '__iter__', False): - # iterable() isn't used because it would give True if labels is a - # string + # iterable() isn't used because it would give True if labels is a + # string assert len(labels) == n, ( "If labels is a list, then labels and flows must have the " "same length.\nlabels has length %d, but flows has length %d." @@ -590,7 +590,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', # Determine the lengths of the bottom-side arrows # from the middle outwards. for i, (angle, is_input, flow) in enumerate(reversed(list(zip( - angles, are_inputs, scaled_flows)))): + angles, are_inputs, scaled_flows)))): if angle == UP and is_input: pathlengths[n - i - 1] = lllength lllength += flow @@ -601,7 +601,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', # from the bottom upwards. has_left_input = False for i, (angle, is_input, spec) in enumerate(reversed(list(zip( - angles, are_inputs, zip(scaled_flows, pathlengths))))): + angles, are_inputs, zip(scaled_flows, pathlengths))))): if angle == RIGHT: if is_input: if has_left_input: @@ -612,7 +612,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', # from the top downwards. has_right_output = False for i, (angle, is_input, spec) in enumerate(zip( - angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): if angle == RIGHT: if not is_input: if has_right_output: @@ -656,7 +656,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', label_locations = np.zeros((n, 2)) # Add the top-side inputs and outputs from the middle outwards. for i, (angle, is_input, spec) in enumerate(zip( - angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): if angle == DOWN and is_input: tips[i, :], label_locations[i, :] = self._add_input( ulpath, angle, *spec) @@ -665,7 +665,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', urpath, angle, *spec) # Add the bottom-side inputs and outputs from the middle outwards. for i, (angle, is_input, spec) in enumerate(reversed(list(zip( - angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): if angle == UP and is_input: tip, label_location = self._add_input(llpath, angle, *spec) tips[n - i - 1, :] = tip @@ -677,7 +677,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', # Add the left-side inputs from the bottom upwards. has_left_input = False for i, (angle, is_input, spec) in enumerate(reversed(list(zip( - angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): + angles, are_inputs, list(zip(scaled_flows, pathlengths)))))): if angle == RIGHT and is_input: if not has_left_input: # Make sure the lower path extends @@ -692,7 +692,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='', # Add the right-side outputs from the top downwards. has_right_output = False for i, (angle, is_input, spec) in enumerate(zip( - angles, are_inputs, list(zip(scaled_flows, pathlengths)))): + angles, are_inputs, list(zip(scaled_flows, pathlengths)))): if angle == RIGHT and not is_input: if not has_right_output: # Make sure the upper path extends diff --git a/lib/matplotlib/tight_layout.py b/lib/matplotlib/tight_layout.py index 08aa09bc0228..251aa5ab6c28 100644 --- a/lib/matplotlib/tight_layout.py +++ b/lib/matplotlib/tight_layout.py @@ -123,9 +123,6 @@ def auto_adjust_subplotpars(fig, renderer, for subplots, ax_bbox, (num1, num2) in zip(subplot_list, ax_bbox_list, num1num2_list): - - #ax_bbox = union([ax.get_position(original=True) for ax in subplots]) - tight_bbox_raw = union([ax.get_tightbbox(renderer) for ax in subplots]) tight_bbox = TransformedBbox(tight_bbox_raw, fig.transFigure.inverted()) @@ -197,7 +194,7 @@ def auto_adjust_subplotpars(fig, renderer, 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 * (cols - 1)) / cols kwargs["wspace"] = hspace / h_axes @@ -299,9 +296,9 @@ def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, ncols_list = [] ax_bbox_list = [] - subplot_dict = {} # multiple axes can share - # same subplot_interface (e.g., axes_grid1). Thus - # we need to join them together. + # multiple axes can share same subplot_interface (e.g., axes_grid1). Thus + # we need to join them together. + subplot_dict = {} subplotspec_list2 = [] From 9e6cf4ff36bcb4d974030f6d8036abe1c6f3f537 Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Tue, 24 Feb 2015 21:36:36 -0800 Subject: [PATCH 3/5] STY: fix line length >79 --- lib/matplotlib/patches.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index 860cc16f2107..fa82e91607cc 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -2316,7 +2316,7 @@ def transmute(self, x0, y0, width, height, mutation_size): saw_vertices = np.concatenate([np.array(saw_vertices), [saw_vertices[0]]], axis=0) codes = ([Path.MOVETO] + - [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1) // 2) + + [Path.CURVE3, Path.CURVE3] * ((len(saw_vertices)-1)//2) + [Path.CLOSEPOLY]) return Path(saw_vertices, codes) From a0476c9f8f46f80146d60b98524c170a27614adc Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Tue, 24 Feb 2015 22:02:46 -0800 Subject: [PATCH 4/5] STY: More travis pep8 fixes --- lib/matplotlib/backends/backend_pdf.py | 29 ++++++++++++-------------- lib/matplotlib/tests/test_pickle.py | 1 - 2 files changed, 13 insertions(+), 17 deletions(-) diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 62191d1982f3..2fe7e22283f6 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -462,8 +462,8 @@ def __init__(self, filename): self.fontNames = {} # maps filenames to internal font names self.nextFont = 1 # next free internal font name self.dviFontInfo = {} # information on dvi fonts - self.type1Descriptors = {} # differently encoded Type-1 fonts may - # share the same descriptor + # differently encoded Type-1 fonts may share the same descriptor + self.type1Descriptors = {} self.used_characters = {} self.alphaStates = {} # maps alpha values to graphics state objects @@ -480,8 +480,7 @@ def __init__(self, filename): self.paths = [] - self.pageAnnotations = [] # A list of annotations for the - # current page + self.pageAnnotations = [] # A list of annotations for the current page # The PDF spec recommends to include every procset procsets = [Name(x) @@ -769,7 +768,7 @@ def createType1Descriptor(self, t1font, fontfile): 'FontFamily': t1font.prop['FamilyName'], 'StemV': 50, # TODO # (see also revision 3874; but not all TeX distros have AFM files!) - #'FontWeight': a number where 400 = Regular, 700 = Bold + # 'FontWeight': a number where 400 = Regular, 700 = Bold } self.writeObject(fontdescObject, descriptor) @@ -1251,8 +1250,8 @@ def imageObject(self, image): self.images[image] = (name, ob) return name - ## These two from backend_ps.py - ## TODO: alpha (SMask, p. 518 of pdf spec) + # These two from backend_ps.py + # TODO: alpha (SMask, p. 518 of pdf spec) def _rgb(self, im): h, w, s = im.as_rgba_str() @@ -1710,10 +1709,8 @@ def draw_markers(self, gc, marker_path, marker_trans, path, trans, simplify=False): if len(vertices): x, y = vertices[-2:] - if (x < 0 or - y < 0 or - x > self.file.width * 72 or - y > self.file.height * 72): + if (x < 0 or y < 0 or + x > self.file.width * 72 or y > self.file.height * 72): continue dx, dy = x - lastx, y - lasty output(1, 0, 0, 1, dx, dy, Op.concat_matrix, @@ -1970,8 +1967,8 @@ def check_simple_method(s): chunks[-1][1].append(c) else: chunks.append((char_type, [c])) - use_simple_method = (len(chunks) == 1 - and chunks[-1][0] == 1) + use_simple_method = (len(chunks) == 1 and + chunks[-1][0] == 1) return use_simple_method, chunks def draw_text_simple(): @@ -2255,7 +2252,7 @@ def clip_cmd(self, cliprect, clippath): cmds.extend(self.pop()) # Unless we hit the right one, set the clip polygon if ((self._cliprect, self._clippath) != (cliprect, clippath) or - self.parent is None): + self.parent is None): cmds.extend(self.push()) if self._cliprect != cliprect: cmds.extend([cliprect, Op.rectangle, Op.clip, Op.endpath]) @@ -2417,8 +2414,8 @@ def close(self): PDF file. """ self._file.close() - if (self.get_pagecount() == 0 and not self.keep_empty - and not self._file.passed_in_file_object): + if (self.get_pagecount() == 0 and not self.keep_empty and + not self._file.passed_in_file_object): os.remove(self._file.fh.name) self._file = None diff --git a/lib/matplotlib/tests/test_pickle.py b/lib/matplotlib/tests/test_pickle.py index 0c289c2c702a..f41c2fad16b5 100644 --- a/lib/matplotlib/tests/test_pickle.py +++ b/lib/matplotlib/tests/test_pickle.py @@ -83,7 +83,6 @@ def recursive_pickle(top_obj): objs = sorted(six.itervalues(objs), key=lambda val: (-val[0], val[2])) for _, obj, location in objs: -# print('trying %s' % location) try: pickle.dump(obj, BytesIO(), pickle.HIGHEST_PROTOCOL) except Exception as err: From dfed541790553b93b9f1058459c9a367def64f2a Mon Sep 17 00:00:00 2001 From: Cimarron Mittelsteadt Date: Wed, 25 Feb 2015 20:33:58 -0800 Subject: [PATCH 5/5] STY: Reversed E113 pep errors where the indenting of comments looked fine. Also addressed comments from @efiring --- examples/pylab_examples/multipage_pdf.py | 4 +-- .../tricontour_smooth_delaunay.py | 25 +++++++++---------- examples/user_interfaces/embedding_in_tk.py | 5 ++-- lib/matplotlib/backends/backend_pdf.py | 7 +++--- lib/matplotlib/colors.py | 10 ++------ lib/matplotlib/contour.py | 4 +-- lib/matplotlib/image.py | 7 +++--- lib/matplotlib/quiver.py | 24 ++++++++++-------- lib/matplotlib/tight_layout.py | 6 ++--- 9 files changed, 43 insertions(+), 49 deletions(-) diff --git a/examples/pylab_examples/multipage_pdf.py b/examples/pylab_examples/multipage_pdf.py index 07ab80ab1b2c..c32b73bee3ec 100644 --- a/examples/pylab_examples/multipage_pdf.py +++ b/examples/pylab_examples/multipage_pdf.py @@ -23,8 +23,8 @@ x = np.arange(0, 5, 0.1) plt.plot(x, np.sin(x), 'b-') plt.title('Page Two') - # you can add a pdf note to attach metadata to a page - pdf.attach_note("plot of sin(x)") + pdf.attach_note("plot of sin(x)") # you can add a pdf note to + # attach metadata to a page pdf.savefig() plt.close() diff --git a/examples/pylab_examples/tricontour_smooth_delaunay.py b/examples/pylab_examples/tricontour_smooth_delaunay.py index b485ffbcd1d3..a155347dcb90 100644 --- a/examples/pylab_examples/tricontour_smooth_delaunay.py +++ b/examples/pylab_examples/tricontour_smooth_delaunay.py @@ -45,19 +45,18 @@ def experiment_res(x, y): # User parameters for data test points n_test = 200 # Number of test data points, tested from 3 to 5000 for subdiv=3 -# Number of recursive subdivisions of the initial mesh for smooth plots. -# Values >3 might result in a very high number of triangles for the refine -# mesh: new triangles numbering = (4**subdiv)*ntri -subdiv = 3 - -# Float > 0. adjusting the proportion of (invalid) initial triangles which will -# be masked out. Enter 0 for no mask. -init_mask_frac = 0.0 - -# Minimum circle ratio - border triangles with circle ratio below this will -# be masked if they touch a border. Suggested value 0.01; Use -1 to keep -# all triangles. -min_circle_ratio = .01 +subdiv = 3 # Number of recursive subdivisions of the initial mesh for smooth + # plots. Values >3 might result in a very high number of triangles + # for the refine mesh: new triangles numbering = (4**subdiv)*ntri + +init_mask_frac = 0.0 # Float > 0. adjusting the proportion of + # (invalid) initial triangles which will be masked + # out. Enter 0 for no mask. + +min_circle_ratio = .01 # Minimum circle ratio - border triangles with circle + # ratio below this will be masked if they touch a + # border. Suggested value 0.01 ; Use -1 to keep + # all triangles. # Random points random_gen = np.random.mtrand.RandomState(seed=127260) diff --git a/examples/user_interfaces/embedding_in_tk.py b/examples/user_interfaces/embedding_in_tk.py index 6ff0ba13ebf8..4c93d25a9c84 100755 --- a/examples/user_interfaces/embedding_in_tk.py +++ b/examples/user_interfaces/embedding_in_tk.py @@ -48,9 +48,8 @@ def on_key_event(event): def _quit(): root.quit() # stops mainloop - # this is necessary on Windows to prevent - # Fatal Python Error: PyEval_RestoreThread: NULL tstate - root.destroy() + root.destroy() # this is necessary on Windows to prevent + # Fatal Python Error: PyEval_RestoreThread: NULL tstate button = Tk.Button(master=root, text='Quit', command=_quit) button.pack(side=Tk.BOTTOM) diff --git a/lib/matplotlib/backends/backend_pdf.py b/lib/matplotlib/backends/backend_pdf.py index 2fe7e22283f6..e03ab01ade93 100644 --- a/lib/matplotlib/backends/backend_pdf.py +++ b/lib/matplotlib/backends/backend_pdf.py @@ -462,8 +462,8 @@ def __init__(self, filename): self.fontNames = {} # maps filenames to internal font names self.nextFont = 1 # next free internal font name self.dviFontInfo = {} # information on dvi fonts - # differently encoded Type-1 fonts may share the same descriptor - self.type1Descriptors = {} + self.type1Descriptors = {} # differently encoded Type-1 fonts may + # share the same descriptor self.used_characters = {} self.alphaStates = {} # maps alpha values to graphics state objects @@ -480,7 +480,8 @@ def __init__(self, filename): self.paths = [] - self.pageAnnotations = [] # A list of annotations for the current page + self.pageAnnotations = [] # A list of annotations for the + # current page # The PDF spec recommends to include every procset procsets = [Name(x) diff --git a/lib/matplotlib/colors.py b/lib/matplotlib/colors.py index fbc5cdcafa9a..6686ce8aa2f4 100644 --- a/lib/matplotlib/colors.py +++ b/lib/matplotlib/colors.py @@ -482,8 +482,6 @@ def makeMappingArray(N, data, gamma=1.0): lut[-1] = y0[-1] # ensure that the lut is confined to values between 0 and 1 by clipping it np.clip(lut, 0.0, 1.0) - # lut = where(lut > 1., 1., lut) - # lut = where(lut < 0., 0., lut) return lut @@ -614,9 +612,6 @@ def __call__(self, X, alpha=None, bytes=False): rgba = np.empty(shape=xa.shape + (4,), dtype=lut.dtype) lut.take(xa, axis=0, mode='clip', out=rgba) - # twice as fast as lut[xa]; - # using the clip or wrap mode and providing an - # output array speeds it up a little more. if vtype == 'scalar': rgba = tuple(rgba[0, :]) return rgba @@ -810,8 +805,8 @@ def __init__(self, colors, name='from_list', N=None): the list will be extended by repetition. """ self.colors = colors - # True only if all colors in map are identical; needed for contouring. - self.monochrome = False + self.monochrome = False # True only if all colors in map are + # identical; needed for contouring. if N is None: N = len(self.colors) else: @@ -1384,7 +1379,6 @@ def hsv_to_rgb(hsv): rgb : (..., 3) ndarray Colors converted to RGB values in range [0, 1] """ - # make sure it is an ndarray hsv = np.asarray(hsv) # check length of the last dimension, should be _some_ sort of rgb diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 5eb67a1ba446..4bceb7417d60 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -838,8 +838,8 @@ def __init__(self, ax, *args, **kwargs): self.extend = kwargs.get('extend', 'neither') self.antialiased = kwargs.get('antialiased', None) if self.antialiased is None and self.filled: - # eliminate artifacts; we are not stroking the boundaries - self.antialiased = False + self.antialiased = False # eliminate artifacts; we are not + # stroking the boundaries. # The default for line contours will be taken from # the LineCollection default, which uses the # rcParams['lines.antialiased'] diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 0e3f633107d7..2428147218bb 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -331,10 +331,9 @@ def _draw_unsampled_image(self, renderer, gc): if numrows <= 0 or numcols <= 0: return - - # just to create im.bufOut that is required by backends. There may be - # a better solution -JJL - im.resize(numcols, numrows) + im.resize(numcols, numrows) # just to create im.bufOut that + # is required by backends. There + # may be better solution -JJL im._url = self.get_url() im._gid = self.get_gid() diff --git a/lib/matplotlib/quiver.py b/lib/matplotlib/quiver.py index f547329687d1..218ee5355539 100644 --- a/lib/matplotlib/quiver.py +++ b/lib/matplotlib/quiver.py @@ -249,9 +249,10 @@ def on_dpi_change(fig): self_weakref = weak_self() if self_weakref is not None: self_weakref.labelsep = (self_weakref._labelsep_inches*fig.dpi) - # simple brute force update works because _init is called at - # the start of draw - self_weakref._initialized = False + self_weakref._initialized = False # simple brute force update + # works because _init is + # called at the start of + # draw. self._cid = Q.ax.figure.callbacks.connect('dpi_changed', on_dpi_change) @@ -467,11 +468,12 @@ def __init__(self, ax, *args, **kw): def on_dpi_change(fig): self_weakref = weak_self() if self_weakref is not None: - # vertices depend on width, span which in turn depend on dpi - self_weakref._new_UV = True - # simple brute force update works because _init is called at - # the start of draw - self_weakref._initialized = False + self_weakref._new_UV = True # vertices depend on width, span + # which in turn depend on dpi + self_weakref._initialized = False # simple brute force update + # works because _init is + # called at the start of + # draw. self._cid = self.ax.figure.callbacks.connect('dpi_changed', on_dpi_change) @@ -698,9 +700,9 @@ def _h_arrows(self, length): if self.pivot == 'middle': X -= 0.5 * X[:, 3, np.newaxis] elif self.pivot == 'tip': - # numpy bug? using -= does not work here unless we multiply by a - # float first, as with 'mid'. - X = X - X[:, 3, np.newaxis] + X = X - X[:, 3, np.newaxis] # numpy bug? using -= does not + # work here unless we multiply + # by a float first, as with 'mid'. tooshort = length < self.minlength if tooshort.any(): # Use a heptagonal dot: diff --git a/lib/matplotlib/tight_layout.py b/lib/matplotlib/tight_layout.py index 251aa5ab6c28..174b2efeeb35 100644 --- a/lib/matplotlib/tight_layout.py +++ b/lib/matplotlib/tight_layout.py @@ -296,9 +296,9 @@ def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer, ncols_list = [] ax_bbox_list = [] - # multiple axes can share same subplot_interface (e.g., axes_grid1). Thus - # we need to join them together. - subplot_dict = {} + subplot_dict = {} # multiple axes can share + # same subplot_interface (e.g., axes_grid1). Thus + # we need to join them together. subplotspec_list2 = []