From f217ae6e93263abafa16c7ef845bddb65567f25c Mon Sep 17 00:00:00 2001 From: Nelle Varoquaux Date: Fri, 5 Oct 2012 20:33:31 +0200 Subject: [PATCH 1/2] PEP8 fixes on axes.py --- lib/matplotlib/axes.py | 1638 +++++++++++++++++++++------------------- 1 file changed, 850 insertions(+), 788 deletions(-) diff --git a/lib/matplotlib/axes.py b/lib/matplotlib/axes.py index c3f9afb3fed3..9bdd427fc1fa 100644 --- a/lib/matplotlib/axes.py +++ b/lib/matplotlib/axes.py @@ -1,5 +1,8 @@ from __future__ import division, print_function -import math, sys, warnings, datetime +import math +import sys +import warnings +import datetime from operator import itemgetter import itertools @@ -16,7 +19,7 @@ import matplotlib.collections as mcoll import matplotlib.colors as mcolors import matplotlib.contour as mcontour -import matplotlib.dates as _ # <-registers a date unit converter +import matplotlib.dates as _ # <-registers a date unit converter from matplotlib import docstring import matplotlib.font_manager as font_manager import matplotlib.image as mimage @@ -42,6 +45,7 @@ is_string_like = cbook.is_string_like is_sequence_of_strings = cbook.is_sequence_of_strings + def _string_to_bool(s): if not is_string_like(s): return s @@ -51,6 +55,7 @@ def _string_to_bool(s): return False raise ValueError("string argument must be either 'on' or 'off'") + def _process_plot_format(fmt): """ Process a MATLAB style color/line style format string. Return a @@ -93,13 +98,13 @@ def _process_plot_format(fmt): # handle the multi char special cases and strip them from the # string - if fmt.find('--')>=0: + if fmt.find('--') >= 0: linestyle = '--' fmt = fmt.replace('--', '') - if fmt.find('-.')>=0: + if fmt.find('-.') >= 0: linestyle = '-.' fmt = fmt.replace('-.', '') - if fmt.find(' ')>=0: + if fmt.find(' ') >= 0: linestyle = 'None' fmt = fmt.replace(' ', '') @@ -134,6 +139,7 @@ def _process_plot_format(fmt): return linestyle, marker, color + def set_default_color_cycle(clist): """ Change the default cycle of colors that will be used by the plot @@ -151,7 +157,7 @@ def set_default_color_cycle(clist): """ rcParams['axes.color_cycle'] = clist warnings.warn("Set rcParams['axes.color_cycle'] directly", - DeprecationWarning) + DeprecationWarning) class _process_plot_var_args(object): @@ -187,36 +193,36 @@ def set_color_cycle(self, clist=None): def __call__(self, *args, **kwargs): if self.axes.xaxis is not None and self.axes.yaxis is not None: - xunits = kwargs.pop( 'xunits', self.axes.xaxis.units) + xunits = kwargs.pop('xunits', self.axes.xaxis.units) if self.axes.name == 'polar': - xunits = kwargs.pop( 'thetaunits', xunits ) - yunits = kwargs.pop( 'yunits', self.axes.yaxis.units) + xunits = kwargs.pop('thetaunits', xunits) + yunits = kwargs.pop('yunits', self.axes.yaxis.units) if self.axes.name == 'polar': - yunits = kwargs.pop( 'runits', yunits ) - if xunits!=self.axes.xaxis.units: + yunits = kwargs.pop('runits', yunits) + if xunits != self.axes.xaxis.units: self.axes.xaxis.set_units(xunits) - if yunits!=self.axes.yaxis.units: + if yunits != self.axes.yaxis.units: self.axes.yaxis.set_units(yunits) - ret = self._grab_next_args(*args, **kwargs) + ret = self._grab_next_args(*args, **kwargs) return ret def set_lineprops(self, line, **kwargs): assert self.command == 'plot', 'set_lineprops only works with "plot"' for key, val in kwargs.items(): - funcName = "set_%s"%key - if not hasattr(line,funcName): - raise TypeError('There is no line property "%s"'%key) - func = getattr(line,funcName) + funcName = "set_%s" % key + if not hasattr(line, funcName): + raise TypeError('There is no line property "%s"' % key) + func = getattr(line, funcName) func(val) def set_patchprops(self, fill_poly, **kwargs): assert self.command == 'fill', 'set_patchprops only works with "fill"' for key, val in kwargs.items(): - funcName = "set_%s"%key - if not hasattr(fill_poly,funcName): - raise TypeError('There is no patch property "%s"'%key) - func = getattr(fill_poly,funcName) + funcName = "set_%s" % key + if not hasattr(fill_poly, funcName): + raise TypeError('There is no patch property "%s"' % key) + func = getattr(fill_poly, funcName) func(val) def _xy_from_xy(self, x, y): @@ -224,7 +230,7 @@ def _xy_from_xy(self, x, y): bx = self.axes.xaxis.update_units(x) by = self.axes.yaxis.update_units(y) - if self.command!='plot': + if self.command != 'plot': # the Line2D class can handle unitized data, with # support for post hoc unit changes etc. Other mpl # artists, eg Polygon which _process_plot_var_args @@ -242,7 +248,7 @@ def _xy_from_xy(self, x, y): if by: y = self.axes.convert_yunits(y) - x = np.atleast_1d(x) #like asanyarray, but converts scalar to array + x = np.atleast_1d(x) # like asanyarray, but converts scalar to array y = np.atleast_1d(y) if x.shape[0] != y.shape[0]: raise ValueError("x and y must have same first dimension") @@ -250,21 +256,21 @@ def _xy_from_xy(self, x, y): raise ValueError("x and y can be no greater than 2-D") if x.ndim == 1: - x = x[:,np.newaxis] + x = x[:, np.newaxis] if y.ndim == 1: - y = y[:,np.newaxis] + y = y[:, np.newaxis] return x, y def _makeline(self, x, y, kw, kwargs): - kw = kw.copy() # Don't modify the original kw. + kw = kw.copy() # Don't modify the original kw. if not 'color' in kw and not 'color' in kwargs.keys(): kw['color'] = self.color_cycle.next() # (can't use setdefault because it always evaluates # its second argument) seg = mlines.Line2D(x, y, - axes=self.axes, - **kw - ) + axes=self.axes, + **kw + ) self.set_lineprops(seg, **kwargs) return seg @@ -274,15 +280,14 @@ def _makefill(self, x, y, kw, kwargs): except KeyError: facecolor = self.color_cycle.next() seg = mpatches.Polygon(np.hstack( - (x[:,np.newaxis],y[:,np.newaxis])), - facecolor = facecolor, - fill=True, - closed=kw['closed'] - ) + (x[:, np.newaxis], y[:, np.newaxis])), + facecolor=facecolor, + fill=True, + closed=kw['closed'] + ) self.set_patchprops(seg, **kwargs) return seg - def _plot_args(self, tup, kwargs): ret = [] if len(tup) > 1 and is_string_like(tup[-1]): @@ -315,7 +320,7 @@ def _plot_args(self, tup, kwargs): ncx, ncy = x.shape[1], y.shape[1] for j in xrange(max(ncx, ncy)): - seg = func(x[:,j%ncx], y[:,j%ncy], kw, kwargs) + seg = func(x[:, j % ncx], y[:, j % ncy], kw, kwargs) ret.append(seg) return ret @@ -324,7 +329,7 @@ def _grab_next_args(self, *args, **kwargs): remaining = args while 1: - if len(remaining)==0: + if len(remaining) == 0: return if len(remaining) <= 3: for seg in self._plot_args(remaining, kwargs): @@ -338,7 +343,7 @@ def _grab_next_args(self, *args, **kwargs): for seg in self._plot_args(remaining[:isplit], kwargs): yield seg - remaining=remaining[isplit:] + remaining = remaining[isplit:] class Axes(martist.Artist): @@ -364,10 +369,10 @@ def __str__(self): return "Axes(%g,%g;%gx%g)" % tuple(self._position.bounds) def __init__(self, fig, rect, - axisbg = None, # defaults to rc axes.facecolor - frameon = True, - sharex=None, # use Axes instance's xaxis info - sharey=None, # use Axes instance's yaxis info + axisbg=None, # defaults to rc axes.facecolor + frameon=True, + sharex=None, # use Axes instance's xaxis info + sharey=None, # use Axes instance's yaxis info label='', xscale=None, yscale=None, @@ -460,7 +465,8 @@ def __init__(self, fig, rect, # this call may differ for non-sep axes, eg polar self._init_axis() - if axisbg is None: axisbg = rcParams['axes.facecolor'] + if axisbg is None: + axisbg = rcParams['axes.facecolor'] self._axisbg = axisbg self._frameon = frameon self._axisbelow = rcParams['axes.axisbelow'] @@ -468,26 +474,25 @@ def __init__(self, fig, rect, self._rasterization_zorder = None self._hold = rcParams['axes.hold'] - self._connected = {} # a dict from events to (id, func) + self._connected = {} # a dict from events to (id, func) self.cla() # funcs used to format x and y - fall back on major formatters self.fmt_xdata = None self.fmt_ydata = None - - self.set_cursor_props((1,'k')) # set the cursor properties for axes + self.set_cursor_props((1, 'k')) # set the cursor properties for axes self._cachedRenderer = None self.set_navigate(True) self.set_navigate_mode(None) - if xscale: self.set_xscale(xscale) if yscale: self.set_yscale(yscale) - if len(kwargs): martist.setp(self, **kwargs) + if len(kwargs): + martist.setp(self, **kwargs) if self.xaxis is not None: self._xcid = self.xaxis.callbacks.connect('units finalize', @@ -531,7 +536,8 @@ def set_figure(self, fig): """ martist.Artist.set_figure(self, fig) - self.bbox = mtransforms.TransformedBbox(self._position, fig.transFigure) + self.bbox = mtransforms.TransformedBbox( + self._position, fig.transFigure) #these will be updated later as data is added self.dataLim = mtransforms.Bbox.unit() self.viewLim = mtransforms.Bbox.unit() @@ -576,11 +582,11 @@ def _set_lim_and_transforms(self): self.transData = self.transScale + (self.transLimits + self.transAxes) self._xaxis_transform = mtransforms.blended_transform_factory( - self.transData, self.transAxes) + self.transData, self.transAxes) self._yaxis_transform = mtransforms.blended_transform_factory( - self.transAxes, self.transData) + self.transAxes, self.transData) - def get_xaxis_transform(self,which='grid'): + def get_xaxis_transform(self, which='grid'): """ Get the transformation used for drawing x-axis labels, ticks and gridlines. The x-direction is in data coordinates and the @@ -594,12 +600,12 @@ def get_xaxis_transform(self,which='grid'): place axis elements in different locations. """ - if which=='grid': + if which == 'grid': return self._xaxis_transform - elif which=='tick1': + elif which == 'tick1': # for cartesian projection, this is bottom spine return self.spines['bottom'].get_spine_transform() - elif which=='tick2': + elif which == 'tick2': # for cartesian projection, this is top spine return self.spines['top'].get_spine_transform() else: @@ -657,7 +663,7 @@ def get_xaxis_text2_transform(self, pad_points): self.figure.dpi_scale_trans), "bottom", "center") - def get_yaxis_transform(self,which='grid'): + def get_yaxis_transform(self, which='grid'): """ Get the transformation used for drawing y-axis labels, ticks and gridlines. The x-direction is in axis coordinates and the @@ -671,12 +677,12 @@ def get_yaxis_transform(self,which='grid'): place axis elements in different locations. """ - if which=='grid': + if which == 'grid': return self._yaxis_transform - elif which=='tick1': + elif which == 'tick1': # for cartesian projection, this is bottom spine return self.spines['left'].get_spine_transform() - elif which=='tick2': + elif which == 'tick2': # for cartesian projection, this is top spine return self.spines['right'].get_spine_transform() else: @@ -705,7 +711,7 @@ def get_yaxis_text1_transform(self, pad_points): """ return (self.get_yaxis_transform(which='tick1') + mtransforms.ScaledTranslation(-1 * pad_points / 72.0, 0, - self.figure.dpi_scale_trans), + self.figure.dpi_scale_trans), "center", "right") def get_yaxis_text2_transform(self, pad_points): @@ -731,7 +737,7 @@ def get_yaxis_text2_transform(self, pad_points): """ return (self.get_yaxis_transform(which='tick2') + mtransforms.ScaledTranslation(pad_points / 72.0, 0, - self.figure.dpi_scale_trans), + self.figure.dpi_scale_trans), "center", "left") def _update_transScale(self): @@ -752,7 +758,6 @@ def get_position(self, original=False): else: return self._position.frozen() - def set_position(self, pos, which='both'): """ Set the axes position with:: @@ -845,18 +850,18 @@ def _gen_axes_spines(self, locations=None, offset=0.0, units='inches'): """ return { - 'left':mspines.Spine.linear_spine(self,'left'), - 'right':mspines.Spine.linear_spine(self,'right'), - 'bottom':mspines.Spine.linear_spine(self,'bottom'), - 'top':mspines.Spine.linear_spine(self,'top'), - } + 'left': mspines.Spine.linear_spine(self, 'left'), + 'right': mspines.Spine.linear_spine(self, 'right'), + 'bottom': mspines.Spine.linear_spine(self, 'bottom'), + 'top': mspines.Spine.linear_spine(self, 'top'), + } def cla(self): """Clear the current axes.""" # Note: this is called by Axes.__init__() self.xaxis.cla() self.yaxis.cla() - for name,spine in self.spines.iteritems(): + for name, spine in self.spines.iteritems(): spine.cla() self.ignore_existing_data_limits = True @@ -927,23 +932,22 @@ def cla(self): self.tables = [] self.artists = [] self.images = [] - self._current_image = None # strictly for pyplot via _sci, _gci + self._current_image = None # strictly for pyplot via _sci, _gci self.legend_ = None self.collections = [] # collection.Collection instances - self.containers = [] # + self.containers = [] self.grid(self._gridOn) props = font_manager.FontProperties(size=rcParams['axes.titlesize']) - self.titleOffsetTrans = mtransforms.ScaledTranslation( 0.0, 5.0 / 72.0, self.figure.dpi_scale_trans) - self.title = mtext.Text( + self.title = mtext.Text( x=0.5, y=1.0, text='', fontproperties=props, verticalalignment='baseline', horizontalalignment='center', - ) + ) self.title.set_transform(self.transAxes + self.titleOffsetTrans) self.title.set_clip_box(None) @@ -985,7 +989,6 @@ def set_color_cycle(self, clist): self._get_lines.set_color_cycle(clist) self._get_patches_for_fill.set_color_cycle(clist) - def ishold(self): """return the HOLD status of the axes""" return self._hold @@ -1071,7 +1074,7 @@ def set_aspect(self, aspect, adjustable=None, anchor=None): elif aspect == 'equal': self._aspect = 'equal' else: - self._aspect = float(aspect) # raise ValueError if necessary + self._aspect = float(aspect) # raise ValueError if necessary if adjustable is not None: self.set_adjustable(adjustable) @@ -1120,7 +1123,7 @@ def set_anchor(self, anchor): self._anchor = anchor else: raise ValueError('argument must be among %s' % - ', '.join(mtransforms.Bbox.coefs.keys())) + ', '.join(mtransforms.BBox.coefs.keys())) def get_data_ratio(self): """ @@ -1129,28 +1132,26 @@ def get_data_ratio(self): This method is intended to be overridden by new projection types. """ - 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) + xmin, xmax = self.get_xbound() + ymin, ymax = self.get_ybound() - return ysize/xsize + xsize = max(math.fabs(xmax - xmin), 1e-30) + ysize = max(math.fabs(ymax - ymin), 1e-30) + return ysize / xsize def get_data_ratio_log(self): """ Returns the aspect ratio of the raw data in log scale. Will be used when both axis scales are in log. """ - 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) + xmin, xmax = self.get_xbound() + ymin, ymax = self.get_ybound() - return ysize/xsize + xsize = max(math.fabs(math.log10(xmax) - math.log10(xmin)), 1e-30) + ysize = max(math.fabs(math.log10(ymax) - math.log10(ymin)), 1e-30) + return ysize / xsize def apply_aspect(self, position=None): """ @@ -1160,7 +1161,6 @@ def apply_aspect(self, position=None): if position is None: position = self.get_position(original=True) - aspect = self.get_aspect() if self.name != 'polar': @@ -1173,16 +1173,16 @@ def apply_aspect(self, position=None): (xscale == "log" and yscale == "linear"): if aspect is not "auto": warnings.warn( - 'aspect is not supported for Axes with xscale=%s, yscale=%s' \ + 'aspect is not supported for Axes with xscale=%s, yscale=%s' % (xscale, yscale)) aspect = "auto" - else: # some custom projections have their own scales. + else: # some custom projections have their own scales. pass else: aspect_scale_mode = "linear" if aspect == 'auto': - self.set_position( position , which='active') + self.set_position(position, which='active') return if aspect == 'equal': @@ -1198,8 +1198,8 @@ def apply_aspect(self, position=None): warnings.warn( 'shared axes: "adjustable" is being changed to "datalim"') - figW,figH = self.get_figure().get_size_inches() - fig_aspect = figH/figW + figW, figH = self.get_figure().get_size_inches() + fig_aspect = figH / figW if self._adjustable in ['box', 'box-forced']: if aspect_scale_mode == "log": box_aspect = A * self.get_data_ratio_log() @@ -1214,23 +1214,21 @@ def apply_aspect(self, position=None): # by prior use of 'box' self.set_position(position, which='active') - - xmin,xmax = self.get_xbound() - ymin,ymax = self.get_ybound() + xmin, xmax = self.get_xbound() + ymin, ymax = self.get_ybound() if aspect_scale_mode == "log": 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(math.fabs(xmax - xmin), 1e-30) + ysize = max(math.fabs(ymax - ymin), 1e-30) - l,b,w,h = position.bounds - box_aspect = fig_aspect * (h/w) + l, b, w, h = position.bounds + box_aspect = fig_aspect * (h / w) data_ratio = box_aspect / A - y_expander = (data_ratio*xsize/ysize - 1.0) + 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: @@ -1277,23 +1275,23 @@ def apply_aspect(self, position=None): else: adjy = y_expander > 0 #print 'y_expander, adjy', y_expander, adjy - adjust_y = changey or adjy #(Ymarg > xmarg) + adjust_y = changey or adjy # (Ymarg > xmarg) if adjust_y: - yc = 0.5*(ymin+ymax) - y0 = yc - Ysize/2.0 - y1 = yc + Ysize/2.0 + yc = 0.5 * (ymin + ymax) + y0 = yc - Ysize / 2.0 + y1 = yc + Ysize / 2.0 if aspect_scale_mode == "log": - self.set_ybound((10.**y0, 10.**y1)) + 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 - x1 = xc + Xsize/2.0 + xc = 0.5 * (xmin + xmax) + x0 = xc - Xsize / 2.0 + x1 = xc + Xsize / 2.0 if aspect_scale_mode == "log": - self.set_xbound((10.**x0, 10.**x1)) + self.set_xbound((10. ** x0, 10. ** x1)) else: self.set_xbound((x0, x1)) #print 'New x0, x1:', x0, x1 @@ -1313,21 +1311,23 @@ def axis(self, *v, **kwargs): ymin, ymax = self.get_ylim() return xmin, xmax, ymin, ymax - if len(v)==1 and is_string_like(v[0]): + if len(v) == 1 and is_string_like(v[0]): s = v[0].lower() - if s=='on': self.set_axis_on() - elif s=='off': self.set_axis_off() + if s == 'on': + self.set_axis_on() + elif s == 'off': + self.set_axis_off() elif s in ('equal', 'tight', 'scaled', 'normal', 'auto', 'image'): self.set_autoscale_on(True) self.set_aspect('auto') self.autoscale_view(tight=False) # self.apply_aspect() - if s=='equal': + if s == 'equal': self.set_aspect('equal', adjustable='datalim') elif s == 'scaled': self.set_aspect('equal', adjustable='box', anchor='C') - self.set_autoscale_on(False) # Req. by Mark Bakker - elif s=='tight': + self.set_autoscale_on(False) # Req. by Mark Bakker + elif s == 'tight': self.autoscale_view(tight=True) self.set_autoscale_on(False) elif s == 'image': @@ -1348,16 +1348,16 @@ def axis(self, *v, **kwargs): except IndexError: xmin = kwargs.get('xmin', None) xmax = kwargs.get('xmax', None) - auto = False # turn off autoscaling, unless... + auto = False # turn off autoscaling, unless... if xmin is None and xmax is None: - auto = None # leave autoscaling state alone + auto = None # leave autoscaling state alone xmin, xmax = self.set_xlim(xmin, xmax, emit=emit, auto=auto) ymin = kwargs.get('ymin', None) ymax = kwargs.get('ymax', None) - auto = False # turn off autoscaling, unless... + auto = False # turn off autoscaling, unless... if ymin is None and ymax is None: - auto = None # leave autoscaling state alone + auto = None # leave autoscaling state alone ymin, ymax = self.set_ylim(ymin, ymax, emit=emit, auto=auto) return xmin, xmax, ymin, ymax @@ -1403,12 +1403,10 @@ def get_xgridlines(self): """Get the x grid lines as a list of Line2D instances""" return cbook.silent_list('Line2D xgridline', self.xaxis.get_gridlines()) - def get_xticklines(self): """Get the xtick lines as a list of Line2D instances""" return cbook.silent_list('Text xtickline', self.xaxis.get_ticklines()) - def get_yaxis(self): """Return the YAxis instance""" return self.yaxis @@ -1434,7 +1432,7 @@ def _sci(self, im): "ContourSet must be in current Axes") elif im not in self.images and im not in self.collections: raise ValueError( - "Argument must be an image, collection, or ContourSet in this Axes") + "Argument must be an image, collection, or ContourSet in this Axes") self._current_image = im def _gci(self): @@ -1456,7 +1454,7 @@ def has_data(self): len(self.collections) + len(self.images) + len(self.lines) + - len(self.patches))>0 + len(self.patches)) > 0 def add_artist(self, a): """ @@ -1480,7 +1478,7 @@ def add_collection(self, collection, autolim=True): """ label = collection.get_label() if not label: - collection.set_label('_collection%d'%len(self.collections)) + collection.set_label('_collection%d' % len(self.collections)) self.collections.append(collection) self._set_artist_props(collection) @@ -1546,8 +1544,8 @@ def _update_line_limits(self, line): if data_path.vertices.size > 0: updatex, updatey = line_trans.contains_branch_seperately( - self.transData - ) + self.transData + ) self.dataLim.update_from_path(data_path, self.ignore_existing_data_limits, updatex=updatex, @@ -1581,21 +1579,20 @@ def _update_patch_limits(self, patch): # cannot check for '==0' since unitized data may not compare to zero if (isinstance(patch, mpatches.Rectangle) and - ((not patch.get_width()) or (not patch.get_height()))): + ((not patch.get_width()) or (not patch.get_height()))): return vertices = patch.get_path().vertices if vertices.size > 0: 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().\ - contains_branch_seperately(self.transData) + contains_branch_seperately(self.transData) self.update_datalim(xys, updatex=updatex, - updatey=updatey) - + updatey=updatey) def add_table(self, tab): """ @@ -1619,12 +1616,11 @@ def add_container(self, container): """ label = container.get_label() if not label: - container.set_label('_container%d'%len(self.containers)) + container.set_label('_container%d' % len(self.containers)) self.containers.append(container) container.set_remove_method(lambda h: self.containers.remove(h)) return container - def relim(self): """ Recompute the data limits based on current artists. @@ -1649,11 +1645,12 @@ def update_datalim(self, xys, updatex=True, updatey=True): # Otherwise, it will compute the bounds of it's current data # and the data in xydata - if iterable(xys) and not len(xys): return + if iterable(xys) and not len(xys): + return if not ma.isMaskedArray(xys): xys = np.asarray(xys) self.dataLim.update_from_data_xy(xys, self.ignore_existing_data_limits, - updatex=updatex, updatey=updatey) + updatex=updatex, updatey=updatey) self.ignore_existing_data_limits = False def update_datalim_numerix(self, x, y): @@ -1662,7 +1659,8 @@ def update_datalim_numerix(self, x, y): # limits and set the bound to be the bounds of the xydata. # Otherwise, it will compute the bounds of it's current data # and the data in xydata - if iterable(x) and not len(x): return + if iterable(x) and not len(x): + return self.dataLim.update_from_data(x, y, self.ignore_existing_data_limits) self.ignore_existing_data_limits = False @@ -1676,7 +1674,8 @@ def update_datalim_bounds(self, bounds): def _process_unit_info(self, xdata=None, ydata=None, kwargs=None): """Look for unit *kwargs* and update the axis instances as necessary""" - if self.xaxis is None or self.yaxis is None: return + if self.xaxis is None or self.yaxis is None: + return #print 'processing', self.get_geometry() if xdata is not None: @@ -1693,10 +1692,10 @@ def _process_unit_info(self, xdata=None, ydata=None, kwargs=None): # process kwargs 2nd since these will override default units if kwargs is not None: - xunits = kwargs.pop( 'xunits', self.xaxis.units) + xunits = kwargs.pop('xunits', self.xaxis.units) if self.name == 'polar': - xunits = kwargs.pop( 'thetaunits', xunits ) - if xunits!=self.xaxis.units: + 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, @@ -1706,8 +1705,8 @@ def _process_unit_info(self, xdata=None, ydata=None, kwargs=None): yunits = kwargs.pop('yunits', self.yaxis.units) if self.name == 'polar': - yunits = kwargs.pop( 'runits', yunits ) - if yunits!=self.yaxis.units: + 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, @@ -1791,7 +1790,6 @@ def set_ymargin(self, m): raise ValueError("margin must be in range 0 to 1") self._ymargin = m - def margins(self, *args, **kw): """ Set or retrieve autoscaling margins. @@ -1849,7 +1847,6 @@ def margins(self, *args, **kw): self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley) - def set_rasterization_zorder(self, z): """ Set zorder value below which artists will be rasterized. Set @@ -1905,7 +1902,6 @@ def autoscale(self, enable=True, axis='both', tight=None): scaley = self._autoscaleYon self.autoscale_view(tight=tight, scalex=scalex, scaley=scaley) - def autoscale_view(self, tight=None, scalex=True, scaley=True): """ Autoscale the view limits using the data limits. You can @@ -1921,9 +1917,9 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True): """ if tight is None: # if image data only just use the datalim - _tight = self._tight or (len(self.images)>0 and - len(self.lines)==0 and - len(self.patches)==0) + _tight = self._tight or (len(self.images) > 0 and + len(self.lines) == 0 and + len(self.patches) == 0) else: _tight = self._tight = bool(tight) @@ -1939,7 +1935,7 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True): except AttributeError: # Default nonsingular for, e.g., MaxNLocator x0, x1 = mtransforms.nonsingular(x0, x1, increasing=False, - expander=0.05) + expander=0.05) if self._xmargin > 0: delta = (x1 - x0) * self._xmargin x0 -= delta @@ -1958,7 +1954,7 @@ def autoscale_view(self, tight=None, scalex=True, scaley=True): y0, y1 = ylocator.nonsingular(y0, y1) except AttributeError: y0, y1 = mtransforms.nonsingular(y0, y1, increasing=False, - expander=0.05) + expander=0.05) if self._ymargin > 0: delta = (y1 - y0) * self._ymargin y0 -= delta @@ -1977,7 +1973,8 @@ def draw(self, renderer=None, inframe=False): if renderer is None: raise RuntimeError('No renderer defined') - if not self.get_visible(): return + if not self.get_visible(): + return renderer.open_group('axes') locator = self.get_axes_locator() @@ -1987,7 +1984,6 @@ def draw(self, renderer=None, inframe=False): else: self.apply_aspect() - artists = [] artists.extend(self.collections) @@ -2003,7 +1999,8 @@ def draw(self, renderer=None, inframe=False): self.xaxis.set_zorder(2.5) self.yaxis.set_zorder(2.5) artists.extend([self.xaxis, self.yaxis]) - if not inframe: artists.append(self.title) + if not inframe: + artists.append(self.title) artists.extend(self.tables) if self.legend_ is not None: artists.append(self.legend_) @@ -2014,18 +2011,17 @@ def draw(self, renderer=None, inframe=False): if self.axison and self._frameon: artists.extend(self.spines.itervalues()) - dsu = [ (a.zorder, a) for a in artists - if not a.get_animated() ] + dsu = [(a.zorder, a) for a in artists + if not a.get_animated()] # add images to dsu if the backend support compositing. # otherwise, does the manaul compositing without adding images to dsu. - if len(self.images)<=1 or renderer.option_image_nocomposite(): + if len(self.images) <= 1 or renderer.option_image_nocomposite(): dsu.extend([(im.zorder, im) for im in self.images]) _do_composite = False else: _do_composite = True - dsu.sort(key=itemgetter(0)) # rasterize artists with negative zorder @@ -2048,17 +2044,16 @@ def draw(self, renderer=None, inframe=False): # make a composite image blending alpha # list of (mimage.Image, ox, oy) - zorder_images = [(im.zorder, im) for im in self.images \ + zorder_images = [(im.zorder, im) for im in self.images if im.get_visible()] zorder_images.sort(key=lambda x: x[0]) mag = renderer.get_image_magnification() - ims = [(im.make_image(mag),0,0) for z,im in zorder_images] - + ims = [(im.make_image(mag), 0, 0) for z, im in zorder_images] l, b, r, t = self.bbox.extents - width = mag*((round(r) + 0.5) - (round(l) - 0.5)) - height = mag*((round(t) + 0.5) - (round(b) - 0.5)) + width = mag * ((round(r) + 0.5) - (round(l) - 0.5)) + height = mag * ((round(t) + 0.5) - (round(b) - 0.5)) im = mimage.from_images(height, width, ims) @@ -2071,8 +2066,8 @@ def draw(self, renderer=None, inframe=False): gc = renderer.new_gc() gc.set_clip_rectangle(self.bbox) gc.set_clip_path(mtransforms.TransformedPath( - self.patch.get_path(), - self.patch.get_transform())) + self.patch.get_path(), + self.patch.get_transform())) renderer.draw_image(gc, round(l), round(b), im) gc.restore() @@ -2185,10 +2180,10 @@ def grid(self, b=None, which='major', axis='both', **kwargs): b = True b = _string_to_bool(b) - if axis == 'x' or axis == 'both': - self.xaxis.grid(b, which=which, **kwargs) - if axis == 'y' or axis == 'both': - self.yaxis.grid(b, which=which, **kwargs) + if axis == 'x' or axis == 'both': + self.xaxis.grid(b, which=which, **kwargs) + if axis == 'y' or axis == 'both': + self.yaxis.grid(b, which=which, **kwargs) def ticklabel_format(self, **kwargs): """ @@ -2237,7 +2232,7 @@ def ticklabel_format(self, **kwargs): if scilimits is not None: try: m, n = scilimits - m+n+1 # check that both are numbers + m + n + 1 # check that both are numbers except (ValueError, TypeError): raise ValueError("scilimits must be a sequence of 2 integers") if style[:3] == 'sci': @@ -2448,12 +2443,14 @@ def set_xbound(self, lower=None, upper=None): It will not change the _autoscaleXon attribute. """ if upper is None and iterable(lower): - lower,upper = lower + lower, upper = lower - old_lower,old_upper = self.get_xbound() + old_lower, old_upper = self.get_xbound() - if lower is None: lower = old_lower - if upper is None: upper = old_upper + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper if self.xaxis_inverted(): if lower < upper: @@ -2524,7 +2521,7 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw): raise ValueError("unrecognized kwargs: %s" % kw.keys()) if right is None and iterable(left): - left,right = left + left, right = left self._process_unit_info(xdata=(left, right)) if left is not None: @@ -2533,13 +2530,15 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw): right = self.convert_xunits(right) old_left, old_right = self.get_xlim() - if left is None: left = old_left - if right is None: right = old_right + if left is None: + left = old_left + if right is None: + right = old_right - if left==right: + if left == right: warnings.warn(('Attempting to set identical left==right results\n' - + 'in singular transformations; automatically expanding.\n' - + 'left=%s, right=%s') % (left, right)) + + 'in singular transformations; automatically expanding.\n' + + 'left=%s, right=%s') % (left, right)) left, right = mtransforms.nonsingular(left, right, increasing=False) left, right = self.xaxis.limit_range_for_scale(left, right) @@ -2553,9 +2552,9 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw): for other in self._shared_x_axes.get_siblings(self): if other is not self: other.set_xlim(self.viewLim.intervalx, - emit=False, auto=auto) + 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 @@ -2563,7 +2562,7 @@ def set_xlim(self, left=None, right=None, emit=True, auto=False, **kw): def get_xscale(self): return self.xaxis.get_scale() get_xscale.__doc__ = "Return the xaxis scale string: %s""" % ( - ", ".join(mscale.get_scale_names())) + ", ".join(mscale.get_scale_names())) @docstring.dedent_interpd def set_xscale(self, value, **kwargs): @@ -2663,12 +2662,14 @@ def set_ybound(self, lower=None, upper=None): It will not change the _autoscaleYon attribute. """ if upper is None and iterable(lower): - lower,upper = lower + lower, upper = lower - old_lower,old_upper = self.get_ybound() + old_lower, old_upper = self.get_ybound() - if lower is None: lower = old_lower - if upper is None: upper = old_upper + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper if self.yaxis_inverted(): if lower < upper: @@ -2739,7 +2740,7 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw): raise ValueError("unrecognized kwargs: %s" % kw.keys()) if top is None and iterable(bottom): - bottom,top = bottom + bottom, top = bottom if bottom is not None: bottom = self.convert_yunits(bottom) @@ -2748,13 +2749,15 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw): old_bottom, old_top = self.get_ylim() - if bottom is None: bottom = old_bottom - if top is None: top = old_top + if bottom is None: + bottom = old_bottom + if top is None: + top = old_top - if bottom==top: + if bottom == top: warnings.warn(('Attempting to set identical bottom==top results\n' - + 'in singular transformations; automatically expanding.\n' - + 'bottom=%s, top=%s') % (bottom, top)) + + 'in singular transformations; automatically expanding.\n' + + 'bottom=%s, top=%s') % (bottom, top)) bottom, top = mtransforms.nonsingular(bottom, top, increasing=False) bottom, top = self.yaxis.limit_range_for_scale(bottom, top) @@ -2769,9 +2772,9 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw): for other in self._shared_y_axes.get_siblings(self): if other is not self: other.set_ylim(self.viewLim.intervaly, - emit=False, auto=auto) + 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 bottom, top @@ -2779,7 +2782,7 @@ def set_ylim(self, bottom=None, top=None, emit=True, auto=False, **kw): def get_yscale(self): return self.yaxis.get_scale() get_yscale.__doc__ = "Return the yaxis scale string: %s""" % ( - ", ".join(mscale.get_scale_names())) + ", ".join(mscale.get_scale_names())) @docstring.dedent_interpd def set_yscale(self, value, **kwargs): @@ -2885,7 +2888,8 @@ def format_xdata(self, x): self.fmt_xdata if it is callable, else will fall back on the xaxis major formatter """ - try: return self.fmt_xdata(x) + try: + return self.fmt_xdata(x) except TypeError: func = self.xaxis.get_major_formatter().format_data_short val = func(x) @@ -2897,10 +2901,11 @@ def format_ydata(self, y): :attr:`fmt_ydata` attribute if it is callable, else will fall back on the yaxis major formatter """ - try: return self.fmt_ydata(y) + try: + return self.fmt_ydata(y) except TypeError: func = self.yaxis.get_major_formatter().format_data_short - val = func(y) + val = func(y) return val def format_coord(self, x, y): @@ -2913,7 +2918,7 @@ def format_coord(self, x, y): ys = '???' else: ys = self.format_ydata(y) - return 'x=%s y=%s'%(xs,ys) + return 'x=%s y=%s' % (xs, ys) #### Interactive manipulation @@ -2923,7 +2928,7 @@ def can_zoom(self): """ return True - def can_pan(self) : + def can_pan(self): """ Return *True* if this axes supports any pan/zoom button functionality. """ @@ -2976,13 +2981,13 @@ def start_pan(self, x, y, button): """ self._pan_start = cbook.Bunch( - lim = self.viewLim.frozen(), - trans = self.transData.frozen(), - trans_inverse = self.transData.inverted().frozen(), - bbox = self.bbox.frozen(), - x = x, - y = y - ) + lim=self.viewLim.frozen(), + trans=self.transData.frozen(), + trans_inverse=self.transData.inverted().frozen(), + bbox=self.bbox.frozen(), + x=x, + y=y + ) def end_pan(self): """ @@ -3016,25 +3021,25 @@ def drag_pan(self, button, key, x, y): """ def format_deltas(key, dx, dy): - if key=='control': - if(abs(dx)>abs(dy)): + if key == 'control': + if(abs(dx) > abs(dy)): dy = dx else: dx = dy - elif key=='x': + elif key == 'x': dy = 0 - elif key=='y': + elif key == 'y': dx = 0 - elif key=='shift': - if 2*abs(dx) < abs(dy): - dx=0 - elif 2*abs(dy) < abs(dx): - dy=0 - elif(abs(dx)>abs(dy)): - dy=dy/abs(dy)*abs(dx) + elif key == 'shift': + if 2 * abs(dx) < abs(dy): + dx = 0 + elif 2 * abs(dy) < abs(dx): + dy = 0 + elif(abs(dx) > abs(dy)): + dy = dy / abs(dy) * abs(dx) else: - dx=dx/abs(dx)*abs(dy) - return (dx,dy) + dx = dx / abs(dx) * abs(dy) + return (dx, dy) p = self._pan_start dx = x - p.x @@ -3087,13 +3092,13 @@ def set_cursor_props(self, *args): ACCEPTS: a (*float*, *color*) tuple """ - if len(args)==1: + if len(args) == 1: lw, c = args[0] - elif len(args)==2: + elif len(args) == 2: lw, c = args else: raise ValueError('args must be a (linewidth, color) tuple') - c =mcolors.colorConverter.to_rgba(c) + c = mcolors.colorConverter.to_rgba(c) self._cursorProps = lw, c def connect(self, s, func): @@ -3139,13 +3144,14 @@ def get_children(self): children.extend(self.spines.itervalues()) return children - def contains(self,mouseevent): + def contains(self, mouseevent): """ Test whether the mouse event occured in the axes. Returns *True* / *False*, {} """ - if callable(self._contains): return self._contains(self,mouseevent) + if callable(self._contains): + return self._contains(self, mouseevent) return self.patch.contains(mouseevent) @@ -3167,10 +3173,10 @@ def pick(self, *args): each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set """ - if len(args)>1: + if len(args) > 1: raise DeprecationWarning('New pick API implemented -- ' 'see API_CHANGES in the src distribution') - martist.Artist.pick(self,args[0]) + martist.Artist.pick(self, args[0]) def __pick(self, x, y, trans=None, among=None): """ @@ -3192,26 +3198,26 @@ def __pick(self, x, y, trans=None, among=None): """ # MGDTODO: Needs updating if trans is not None: - xywin = trans.transform_point((x,y)) + xywin = trans.transform_point((x, y)) else: - xywin = x,y + xywin = x, y def dist_points(p1, p2): 'return the distance between two points' x1, y1 = p1 x2, y2 = p2 - return math.sqrt((x1-x2)**2+(y1-y2)**2) + return math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2) def dist_x_y(p1, x, y): '*x* and *y* are arrays; return the distance to the closest point' x1, y1 = p1 - return min(np.sqrt((x-x1)**2+(y-y1)**2)) + return min(np.sqrt((x - x1) ** 2 + (y - y1) ** 2)) def dist(a): if isinstance(a, Text): bbox = a.get_window_extent() - l,b,w,h = bbox.bounds - verts = (l,b), (l,b+h), (l+w,b+h), (l+w, b) + l, b, w, h = bbox.bounds + verts = (l, b), (l, b + h), (l + w, b + h), (l + w, b) xt, yt = zip(*verts) elif isinstance(a, Patch): path = a.get_path() @@ -3228,14 +3234,15 @@ def dist(a): if callable(among): artists = filter(test, artists) elif iterable(among): - amongd = dict([(k,1) for k in among]) + amongd = dict([(k, 1) for k in among]) artists = [a for a in artists if a in amongd] elif among is None: pass else: raise ValueError('among must be callable or iterable') - if not len(artists): return None - ds = [ (dist(a),a) for a in artists] + if not len(artists): + return None + ds = [(dist(a), a) for a in artists] ds.sort() return ds[0][1] @@ -3267,14 +3274,15 @@ def set_title(self, label, fontdict=None, **kwargs): for information on how override and the optional args work """ default = { - 'fontsize':rcParams['axes.titlesize'], - 'verticalalignment' : 'baseline', - 'horizontalalignment' : 'center' - } + 'fontsize': rcParams['axes.titlesize'], + 'verticalalignment': 'baseline', + 'horizontalalignment': 'center' + } self.title.set_text(label) self.title.update(default) - if fontdict is not None: self.title.update(fontdict) + if fontdict is not None: + self.title.update(fontdict) self.title.update(kwargs) return self.title @@ -3306,7 +3314,8 @@ def set_xlabel(self, xlabel, fontdict=None, labelpad=None, **kwargs): :meth:`text` for information on how override and the optional args work """ - if labelpad is not None: self.xaxis.labelpad = labelpad + if labelpad is not None: + self.xaxis.labelpad = labelpad return self.xaxis.set_label_text(xlabel, fontdict, **kwargs) def get_ylabel(self): @@ -3337,7 +3346,8 @@ def set_ylabel(self, ylabel, fontdict=None, labelpad=None, **kwargs): :meth:`text` for information on how override and the optional args work """ - if labelpad is not None: self.yaxis.labelpad = labelpad + if labelpad is not None: + self.yaxis.labelpad = labelpad return self.yaxis.set_label_text(ylabel, fontdict, **kwargs) @docstring.dedent_interpd @@ -3391,10 +3401,10 @@ def text(self, x, y, s, fontdict=None, %(Text)s """ default = { - 'verticalalignment' : 'baseline', - 'horizontalalignment' : 'left', - 'transform' : self.transData, - } + 'verticalalignment': 'baseline', + 'horizontalalignment': 'left', + 'transform': self.transData, + } # At some point if we feel confident that TextWithDash # is robust as a drop-in replacement for Text and that @@ -3405,22 +3415,23 @@ def text(self, x, y, s, fontdict=None, if withdash: t = mtext.TextWithDash( x=x, y=y, text=s, - ) + ) else: t = mtext.Text( x=x, y=y, text=s, - ) + ) self._set_artist_props(t) t.update(default) - if fontdict is not None: t.update(fontdict) + if fontdict is not None: + t.update(fontdict) t.update(kwargs) self.texts.append(t) t._remove_method = lambda h: self.texts.remove(h) - #if t.get_clip_on(): t.set_clip_box(self.bbox) - if 'clip_on' in kwargs: t.set_clip_box(self.bbox) + if 'clip_on' in kwargs: + t.set_clip_box(self.bbox) return t @docstring.dedent_interpd @@ -3443,7 +3454,8 @@ def annotate(self, *args, **kwargs): a = mtext.Annotation(*args, **kwargs) a.set_transform(mtransforms.IdentityTransform()) self._set_artist_props(a) - if kwargs.has_key('clip_on'): a.set_clip_path(self.patch) + if 'clip_on' in kwargs: + a.set_clip_path(self.patch) self.texts.append(a) a._remove_method = lambda h: self.texts.remove(h) return a @@ -3503,13 +3515,13 @@ def axhline(self, y=0, xmin=0, xmax=1, **kwargs): # We need to strip away the units for comparison with # non-unitized bounds - self._process_unit_info( ydata=y, kwargs=kwargs ) - yy = self.convert_yunits( y ) - scaley = (yyymax) + self._process_unit_info(ydata=y, kwargs=kwargs) + yy = self.convert_yunits(y) + scaley = (yy < ymin) or (yy > ymax) trans = mtransforms.blended_transform_factory( self.transAxes, self.transData) - l = mlines.Line2D([xmin,xmax], [y,y], transform=trans, **kwargs) + l = mlines.Line2D([xmin, xmax], [y, y], transform=trans, **kwargs) self.add_line(l) self.autoscale_view(scalex=False, scaley=scaley) return l @@ -3567,13 +3579,13 @@ def axvline(self, x=0, ymin=0, ymax=1, **kwargs): # We need to strip away the units for comparison with # non-unitized bounds - self._process_unit_info( xdata=x, kwargs=kwargs ) - xx = self.convert_xunits( x ) - scalex = (xxxmax) + self._process_unit_info(xdata=x, kwargs=kwargs) + xx = self.convert_xunits(x) + scalex = (xx < xmin) or (xx > xmax) trans = mtransforms.blended_transform_factory( self.transData, self.transAxes) - l = mlines.Line2D([x,x], [ymin,ymax] , transform=trans, **kwargs) + l = mlines.Line2D([x, x], [ymin, ymax], transform=trans, **kwargs) self.add_line(l) self.autoscale_view(scalex=scalex, scaley=False) return l @@ -3621,11 +3633,11 @@ def axhspan(self, ymin, ymax, xmin=0, xmax=1, **kwargs): self.transAxes, self.transData) # process the unit information - self._process_unit_info( [xmin, xmax], [ymin, ymax], kwargs=kwargs ) + self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs) # first we need to strip away the units - xmin, xmax = self.convert_xunits( [xmin, xmax] ) - ymin, ymax = self.convert_yunits( [ymin, ymax] ) + xmin, xmax = self.convert_xunits([xmin, xmax]) + ymin, ymax = self.convert_yunits([ymin, ymax]) verts = (xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin) p = mpatches.Polygon(verts, **kwargs) @@ -3677,11 +3689,11 @@ def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs): self.transData, self.transAxes) # process the unit information - self._process_unit_info( [xmin, xmax], [ymin, ymax], kwargs=kwargs ) + self._process_unit_info([xmin, xmax], [ymin, ymax], kwargs=kwargs) # first we need to strip away the units - xmin, xmax = self.convert_xunits( [xmin, xmax] ) - ymin, ymax = self.convert_yunits( [ymin, ymax] ) + xmin, xmax = self.convert_xunits([xmin, xmax]) + ymin, ymax = self.convert_yunits([ymin, ymax]) verts = [(xmin, ymin), (xmin, ymax), (xmax, ymax), (xmax, ymin)] p = mpatches.Polygon(verts, **kwargs) @@ -3690,10 +3702,9 @@ def axvspan(self, xmin, xmax, ymin=0, ymax=1, **kwargs): self.autoscale_view(scaley=False) return p - @docstring.dedent def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', - label='', **kwargs): + label='', **kwargs): """ Plot horizontal lines. @@ -3736,31 +3747,34 @@ def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', # We do the conversion first since not all unitized data is uniform # process the unit information - self._process_unit_info( [xmin, xmax], y, kwargs=kwargs ) - y = self.convert_yunits( y ) + self._process_unit_info([xmin, xmax], y, kwargs=kwargs) + y = self.convert_yunits(y) xmin = self.convert_xunits(xmin) xmax = self.convert_xunits(xmax) - if not iterable(y): y = [y] - if not iterable(xmin): xmin = [xmin] - if not iterable(xmax): xmax = [xmax] + if not iterable(y): + y = [y] + if not iterable(xmin): + xmin = [xmin] + if not iterable(xmax): + xmax = [xmax] y = np.asarray(y) xmin = np.asarray(xmin) xmax = np.asarray(xmax) - if len(xmin)==1: - xmin = np.resize( xmin, y.shape ) - if len(xmax)==1: - xmax = np.resize( xmax, y.shape ) + if len(xmin) == 1: + xmin = np.resize(xmin, y.shape) + if len(xmax) == 1: + xmax = np.resize(xmax, y.shape) - if len(xmin)!=len(y): + if len(xmin) != len(y): raise ValueError('xmin and y are unequal sized sequences') - if len(xmax)!=len(y): + if len(xmax) != len(y): raise ValueError('xmax and y are unequal sized sequences') - verts = [ ((thisxmin, thisy), (thisxmax, thisy)) - for thisxmin, thisxmax, thisy in zip(xmin, xmax, y)] + verts = [((thisxmin, thisy), (thisxmax, thisy)) + for thisxmin, thisxmax, thisy in zip(xmin, xmax, y)] coll = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label) self.add_collection(coll) @@ -3777,12 +3791,11 @@ def hlines(self, y, xmin, xmax, colors='k', linestyles='solid', self.update_datalim(corners) self.autoscale_view() - return coll @docstring.dedent_interpd def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', - label='', **kwargs): + label='', **kwargs): """ Plot vertical lines. @@ -3817,31 +3830,34 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', self._process_unit_info(xdata=x, ydata=[ymin, ymax], kwargs=kwargs) # We do the conversion first since not all unitized data is uniform - x = self.convert_xunits( x ) - ymin = self.convert_yunits( ymin ) - ymax = self.convert_yunits( ymax ) + x = self.convert_xunits(x) + ymin = self.convert_yunits(ymin) + ymax = self.convert_yunits(ymax) - if not iterable(x): x = [x] - if not iterable(ymin): ymin = [ymin] - if not iterable(ymax): ymax = [ymax] + if not iterable(x): + x = [x] + if not iterable(ymin): + ymin = [ymin] + if not iterable(ymax): + ymax = [ymax] x = np.asarray(x) ymin = np.asarray(ymin) ymax = np.asarray(ymax) - if len(ymin)==1: - ymin = np.resize( ymin, x.shape ) - if len(ymax)==1: - ymax = np.resize( ymax, x.shape ) + if len(ymin) == 1: + ymin = np.resize(ymin, x.shape) + if len(ymax) == 1: + ymax = np.resize(ymax, x.shape) - if len(ymin)!=len(x): + if len(ymin) != len(x): raise ValueError('ymin and x are unequal sized sequences') - if len(ymax)!=len(x): + if len(ymax) != len(x): raise ValueError('ymax and x are unequal sized sequences') Y = np.array([ymin, ymax]).T - verts = [ ((thisx, thisymin), (thisx, thisymax)) - for thisx, (thisymin, thisymax) in zip(x,Y)] + verts = [((thisx, thisymin), (thisx, thisymax)) + for thisx, (thisymin, thisymax) in zip(x, Y)] #print 'creating line collection' coll = mcoll.LineCollection(verts, colors=colors, linestyles=linestyles, label=label) @@ -3849,11 +3865,11 @@ def vlines(self, x, ymin, ymax, colors='k', linestyles='solid', coll.update(kwargs) if len(x) > 0: - minx = min( x ) - maxx = max( x ) + minx = min(x) + maxx = max(x) - miny = min( min(ymin), min(ymax) ) - maxy = max( max(ymin), max(ymax) ) + miny = min(min(ymin), min(ymax)) + maxy = max(max(ymin), max(ymax)) corners = (minx, miny), (maxx, maxy) self.update_datalim(corners) @@ -3871,7 +3887,8 @@ def plot(self, *args, **kwargs): optional format string. For example, each of the following is legal:: - plot(x, y) # plot x and y using default line style and color + plot(x, y) + # plot x and y using default line style and color plot(x, y, 'bo') # plot x and y using blue circle markers plot(y) # plot y using x as index array 0..N-1 plot(y, 'r+') # ditto, but with red plusses @@ -3987,10 +4004,11 @@ def plot(self, *args, **kwargs): whether the *x* and *y* axes are autoscaled; the default is *True*. """ - scalex = kwargs.pop( 'scalex', True) - scaley = kwargs.pop( 'scaley', True) + scalex = kwargs.pop('scalex', True) + scaley = kwargs.pop('scaley', True) - if not self._hold: self.cla() + if not self._hold: + self.cla() lines = [] for line in self._get_lines(*args, **kwargs): @@ -4008,7 +4026,8 @@ def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False, Call signature:: - plot_date(x, y, fmt='bo', tz=None, xdate=True, ydate=False, **kwargs) + plot_date( + x, y, fmt='bo', tz=None, xdate=True, ydate=False, **kwargs) Similar to the :func:`~matplotlib.pyplot.plot` command, except the *x* or *y* (or both) data is considered to be dates, and the @@ -4058,7 +4077,8 @@ def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False, floating point dates. """ - if not self._hold: self.cla() + if not self._hold: + self.cla() ret = self.plot(x, y, fmt, **kwargs) @@ -4071,7 +4091,6 @@ def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False, return ret - @docstring.dedent_interpd def loglog(self, *args, **kwargs): """ @@ -4111,7 +4130,8 @@ def loglog(self, *args, **kwargs): .. plot:: mpl_examples/pylab_examples/log_demo.py """ - if not self._hold: self.cla() + if not self._hold: + self.cla() dx = {'basex': kwargs.pop('basex', 10), 'subsx': kwargs.pop('subsx', None), @@ -4125,8 +4145,8 @@ def loglog(self, *args, **kwargs): self.set_xscale('log', **dx) self.set_yscale('log', **dy) - b = self._hold - self._hold = True # we've already processed the hold + b = self._hold + self._hold = True # we've already processed the hold l = self.plot(*args, **kwargs) self._hold = b # restore the hold @@ -4170,15 +4190,16 @@ def semilogx(self, *args, **kwargs): :meth:`loglog` For example code and figure """ - if not self._hold: self.cla() - d = {'basex': kwargs.pop( 'basex', 10), - 'subsx': kwargs.pop( 'subsx', None), + if not self._hold: + self.cla() + d = {'basex': kwargs.pop('basex', 10), + 'subsx': kwargs.pop('subsx', None), 'nonposx': kwargs.pop('nonposx', 'mask'), } self.set_xscale('log', **d) - b = self._hold - self._hold = True # we've already processed the hold + b = self._hold + self._hold = True # we've already processed the hold l = self.plot(*args, **kwargs) self._hold = b # restore the hold return l @@ -4221,14 +4242,15 @@ def semilogy(self, *args, **kwargs): :meth:`loglog` For example code and figure """ - if not self._hold: self.cla() + if not self._hold: + self.cla() d = {'basey': kwargs.pop('basey', 10), 'subsy': kwargs.pop('subsy', None), 'nonposy': kwargs.pop('nonposy', 'mask'), } self.set_yscale('log', **d) - b = self._hold - self._hold = True # we've already processed the hold + b = self._hold + self._hold = True # we've already processed the hold l = self.plot(*args, **kwargs) self._hold = b # restore the hold @@ -4354,7 +4376,7 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, """ Nx = len(x) - if Nx!=len(y): + if Nx != len(y): raise ValueError('x and y must be equal length') x = detrend(np.asarray(x)) @@ -4362,17 +4384,18 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, c = np.correlate(x, y, mode=2) - if normed: c/= np.sqrt(np.dot(x,x) * np.dot(y,y)) + if normed: + c /= np.sqrt(np.dot(x, x) * np.dot(y, y)) - if maxlags is None: maxlags = Nx - 1 + if maxlags is None: + maxlags = Nx - 1 if maxlags >= Nx or maxlags < 1: raise ValueError('maglags must be None or strictly ' - 'positive < %d'%Nx) - - lags = np.arange(-maxlags,maxlags+1) - c = c[Nx-1-maxlags:Nx+maxlags] + 'positive < %d' % Nx) + lags = np.arange(-maxlags, maxlags + 1) + c = c[Nx - 1 - maxlags:Nx + maxlags] if usevlines: a = self.vlines(lags, [0], c, **kwargs) @@ -4385,11 +4408,10 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, b = None return lags, c, a, b - def _get_legend_handles(self, legend_handler_map=None): "return artists that will be used as handles for legend" handles_original = self.lines + self.patches + \ - self.collections + self.containers + self.collections + self.containers # collections handler_map = mlegend.Legend.get_default_handler_map() @@ -4400,14 +4422,13 @@ def _get_legend_handles(self, legend_handler_map=None): handles = [] for h in handles_original: - if h.get_label() == "_nolegend_": #.startswith('_'): + if h.get_label() == "_nolegend_": # .startswith('_'): continue if mlegend.Legend.get_legend_handler(handler_map, h): handles.append(h) return handles - def get_legend_handles_labels(self, legend_handler_map=None): """ Return handles and labels for legend @@ -4430,7 +4451,6 @@ def get_legend_handles_labels(self, legend_handler_map=None): return handles, labels - def legend(self, *args, **kwargs): """ Place a legend on the current axes. @@ -4474,7 +4494,8 @@ def legend(self, *args, **kwargs): or:: - legend( (line1, line2, line3), ('label1', 'label2', 'label3'), loc=2) + legend( + (line1, line2, line3), ('label1', 'label2', 'label3'), loc=2) The location codes are @@ -4596,20 +4617,20 @@ def legend(self, *args, **kwargs): """ - if len(args)==0: + if len(args) == 0: handles, labels = self.get_legend_handles_labels() if len(handles) == 0: warnings.warn("No labeled objects found. " "Use label='...' kwarg on individual plots.") return None - elif len(args)==1: + elif len(args) == 1: # LABELS labels = args[0] handles = [h for h, label in zip(self._get_legend_handles(), labels)] - elif len(args)==2: + elif len(args) == 2: if is_string_like(args[1]) or isinstance(args[1], int): # LABELS, LOC labels, loc = args @@ -4620,18 +4641,15 @@ def legend(self, *args, **kwargs): # LINES, LABELS handles, labels = args - elif len(args)==3: + elif len(args) == 3: # LINES, LABELS, LOC handles, labels, loc = args kwargs['loc'] = loc else: raise TypeError('Invalid arguments to legend') - # Why do we need to call "flatten" here? -JJL # handles = cbook.flatten(handles) - - self.legend_ = mlegend.Legend(self, handles, labels, **kwargs) return self.legend_ @@ -4670,7 +4688,6 @@ def step(self, x, y, *args, **kwargs): return self.plot(x, y, *args, **kwargs) - @docstring.dedent_interpd def bar(self, left, height, width=0.8, bottom=None, **kwargs): """ @@ -4753,7 +4770,8 @@ def bar(self, left, height, width=0.8, bottom=None, **kwargs): .. plot:: mpl_examples/pylab_examples/bar_stacked.py """ - if not self._hold: self.cla() + if not self._hold: + self.cla() color = kwargs.pop('color', None) edgecolor = kwargs.pop('edgecolor', None) linewidth = kwargs.pop('linewidth', None) @@ -4773,6 +4791,7 @@ def bar(self, left, height, width=0.8, bottom=None, **kwargs): orientation = kwargs.pop('orientation', 'vertical') log = kwargs.pop('log', False) label = kwargs.pop('label', '') + def make_iterable(x): if not iterable(x): return [x] @@ -4833,7 +4852,7 @@ def make_iterable(x): else: color = list(mcolors.colorConverter.to_rgba_array(color)) if len(color) == 0: # until to_rgba_array is changed - color = [[0,0,0,0]] + color = [[0, 0, 0, 0]] if len(color) < nbars: color *= nbars @@ -4842,53 +4861,54 @@ def make_iterable(x): else: edgecolor = list(mcolors.colorConverter.to_rgba_array(edgecolor)) if len(edgecolor) == 0: # until to_rgba_array is changed - edgecolor = [[0,0,0,0]] + edgecolor = [[0, 0, 0, 0]] if len(edgecolor) < nbars: edgecolor *= nbars # FIXME: convert the following to proper input validation # raising ValueError; don't use assert for this. - assert len(left)==nbars, "incompatible sizes: argument 'left' must be length %d or scalar" % nbars - assert len(height)==nbars, ("incompatible sizes: argument 'height' must be length %d or scalar" % - nbars) - assert len(width)==nbars, ("incompatible sizes: argument 'width' must be length %d or scalar" % - nbars) - assert len(bottom)==nbars, ("incompatible sizes: argument 'bottom' must be length %d or scalar" % - nbars) + assert len(left) == nbars, "incompatible sizes: argument 'left' must be length %d or scalar" % nbars + assert len(height) == nbars, ("incompatible sizes: argument 'height' must be length %d or scalar" % + nbars) + assert len(width) == nbars, ("incompatible sizes: argument 'width' must be length %d or scalar" % + nbars) + assert len(bottom) == nbars, ("incompatible sizes: argument 'bottom' must be length %d or scalar" % + nbars) patches = [] # lets do some conversions now since some types cannot be # subtracted uniformly if self.xaxis is not None: - left = self.convert_xunits( left ) - width = self.convert_xunits( width ) + left = self.convert_xunits(left) + width = self.convert_xunits(width) if xerr is not None: - xerr = self.convert_xunits( xerr ) + xerr = self.convert_xunits(xerr) if self.yaxis is not None: - bottom = self.convert_yunits( bottom ) - height = self.convert_yunits( height ) + bottom = self.convert_yunits(bottom) + height = self.convert_yunits(height) if yerr is not None: - yerr = self.convert_yunits( yerr ) + yerr = self.convert_yunits(yerr) if align == 'edge': pass elif align == 'center': if orientation == 'vertical': - left = [left[i] - width[i]/2. for i in xrange(len(left))] + left = [left[i] - width[i] / 2. for i in xrange(len(left))] elif orientation == 'horizontal': - bottom = [bottom[i] - height[i]/2. for i in xrange(len(bottom))] + bottom = [bottom[i] - height[i] / + 2. for i in xrange(len(bottom))] else: raise ValueError('invalid alignment: %s' % align) args = zip(left, bottom, width, height, color, edgecolor, linewidth) for l, b, w, h, c, e, lw in args: - if h<0: + if h < 0: b += h h = abs(h) - if w<0: + if w < 0: l += w w = abs(w) r = mpatches.Rectangle( @@ -4897,7 +4917,7 @@ def make_iterable(x): edgecolor=e, linewidth=lw, label='_nolegend_' - ) + ) r.update(kwargs) r.get_path()._interpolation_steps = 100 #print r.get_label(), label, 'label' in kwargs @@ -4905,18 +4925,18 @@ def make_iterable(x): patches.append(r) holdstate = self._hold - self.hold(True) # ensure hold is on before plotting errorbars + self.hold(True) # ensure hold is on before plotting errorbars if xerr is not None or yerr is not None: if orientation == 'vertical': # using list comps rather than arrays to preserve unit info - x = [l+0.5*w for l, w in zip(left, width)] - y = [b+h for b,h in zip(bottom, height)] + x = [l + 0.5 * w for l, w in zip(left, width)] + y = [b + h for b, h in zip(bottom, height)] elif orientation == 'horizontal': # using list comps rather than arrays to preserve unit info - x = [l+w for l,w in zip(left, width)] - y = [b+0.5*h for b,h in zip(bottom, height)] + x = [l + w for l, w in zip(left, width)] + y = [b + 0.5 * h for b, h in zip(bottom, height)] if "label" not in error_kw: error_kw["label"] = '_nolegend_' @@ -4927,14 +4947,14 @@ def make_iterable(x): else: errorbar = None - self.hold(holdstate) # restore previous hold state + self.hold(holdstate) # restore previous hold state if adjust_xlim: xmin, xmax = self.dataLim.intervalx xmin = np.amin([w for w in width if w > 0]) if xerr is not None: xmin = xmin - np.amax(xerr) - xmin = max(xmin*0.9, 1e-100) + xmin = max(xmin * 0.9, 1e-100) self.dataLim.intervalx = (xmin, xmax) if adjust_ylim: @@ -4942,7 +4962,7 @@ def make_iterable(x): ymin = np.amin([h for h in height if h > 0]) if yerr is not None: ymin = ymin - np.amax(yerr) - ymin = max(ymin*0.9, 1e-100) + ymin = max(ymin * 0.9, 1e-100) self.dataLim.intervaly = (ymin, ymax) self.autoscale_view() @@ -5020,8 +5040,9 @@ def barh(self, bottom, width, height=0.8, left=None, **kwargs): %(Rectangle)s """ - patches = self.bar(left=left, height=height, width=width, bottom=bottom, - orientation='horizontal', **kwargs) + patches = self.bar( + left=left, height=height, width=width, bottom=bottom, + orientation='horizontal', **kwargs) return patches @docstring.dedent_interpd @@ -5095,8 +5116,9 @@ def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-', .. plot:: mpl_examples/pylab_examples/stem_plot.py """ - remember_hold=self._hold - if not self._hold: self.cla() + remember_hold = self._hold + if not self._hold: + self.cla() self.hold(True) markerline, = self.plot(x, y, markerfmt, label="_nolegend_") @@ -5106,11 +5128,11 @@ def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-', stemlines = [] for thisx, thisy in zip(x, y): - l, = self.plot([thisx,thisx], [bottom, thisy], linefmt, + l, = self.plot([thisx, thisx], [bottom, thisy], linefmt, label="_nolegend_") stemlines.append(l) - baseline, = self.plot([np.amin(x), np.amax(x)], [bottom,bottom], + baseline, = self.plot([np.amin(x), np.amax(x)], [bottom, bottom], basefmt, label="_nolegend_") self.hold(remember_hold) @@ -5121,7 +5143,6 @@ def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-', return stem_container - def pie(self, x, explode=None, labels=None, colors=None, autopct=None, pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None, radius=None): @@ -5204,16 +5225,19 @@ def pie(self, x, explode=None, labels=None, colors=None, x = np.asarray(x).astype(np.float32) sx = float(x.sum()) - if sx>1: x = np.divide(x,sx) - - if labels is None: labels = ['']*len(x) - if explode is None: explode = [0]*len(x) - assert(len(x)==len(labels)) - assert(len(x)==len(explode)) - if colors is None: colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w') - + if sx > 1: + x = np.divide(x, sx) + + if labels is None: + labels = [''] * len(x) + if explode is None: + explode = [0] * len(x) + assert(len(x) == len(labels)) + assert(len(x) == len(explode)) + if colors is None: + colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k', 'w') - center = 0,0 + center = 0, 0 if radius is None: radius = 1 @@ -5228,15 +5252,15 @@ def pie(self, x, explode=None, labels=None, colors=None, autotexts = [] i = 0 - for frac, label, expl in cbook.safezip(x,labels, explode): + for frac, label, expl in cbook.safezip(x, labels, explode): x, y = center theta2 = theta1 + frac - thetam = 2*math.pi*0.5*(theta1+theta2) - x += expl*math.cos(thetam) - y += expl*math.sin(thetam) + thetam = 2 * math.pi * 0.5 * (theta1 + theta2) + x += expl * math.cos(thetam) + y += expl * math.sin(thetam) - w = mpatches.Wedge((x,y), radius, 360.*theta1, 360.*theta2, - facecolor=colors[i%len(colors)]) + w = mpatches.Wedge((x, y), radius, 360. * theta1, 360. * theta2, + facecolor=colors[i % len(colors)]) slices.append(w) self.add_patch(w) w.set_label(label) @@ -5246,15 +5270,14 @@ def pie(self, x, explode=None, labels=None, colors=None, # add_patch so the figure and transform props will be # set shad = mpatches.Shadow(w, -0.02, -0.02, - #props={'facecolor':w.get_facecolor()} - ) - shad.set_zorder(0.9*w.get_zorder()) + #props={'facecolor':w.get_facecolor()} + ) + shad.set_zorder(0.9 * w.get_zorder()) shad.set_label('_nolegend_') self.add_patch(shad) - - xt = x + labeldistance*radius*math.cos(thetam) - yt = y + labeldistance*radius*math.sin(thetam) + xt = x + labeldistance * radius * math.cos(thetam) + yt = y + labeldistance * radius * math.sin(thetam) label_alignment = xt > 0 and 'left' or 'right' t = self.text(xt, yt, label, @@ -5265,12 +5288,12 @@ def pie(self, x, explode=None, labels=None, colors=None, texts.append(t) if autopct is not None: - xt = x + pctdistance*radius*math.cos(thetam) - yt = y + pctdistance*radius*math.sin(thetam) + xt = x + pctdistance * radius * math.cos(thetam) + yt = y + pctdistance * radius * math.sin(thetam) if is_string_like(autopct): - s = autopct%(100.*frac) + s = autopct % (100. * frac) elif callable(autopct): - s = autopct(100.*frac) + s = autopct(100. * frac) else: raise TypeError( 'autopct must be callable or a format string') @@ -5280,7 +5303,6 @@ def pie(self, x, explode=None, labels=None, colors=None, verticalalignment='center') autotexts.append(t) - theta1 = theta2 i += 1 @@ -5399,10 +5421,12 @@ def errorbar(self, x, y, yerr=None, xerr=None, """ if errorevery < 1: - raise ValueError('errorevery has to be a strictly positive integer') + raise ValueError( + 'errorevery has to be a strictly positive integer') self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs) - if not self._hold: self.cla() + if not self._hold: + self.cla() holdstate = self._hold self._hold = True @@ -5418,44 +5442,51 @@ def errorbar(self, x, y, yerr=None, xerr=None, if xerr is not None: if not iterable(xerr): - xerr = [xerr]*len(x) + xerr = [xerr] * len(x) if yerr is not None: if not iterable(yerr): - yerr = [yerr]*len(y) + yerr = [yerr] * len(y) l0 = None if barsabove and fmt is not None: - l0, = self.plot(x,y,fmt,label="_nolegend_", **kwargs) + l0, = self.plot(x, y, fmt, label="_nolegend_", **kwargs) barcols = [] caplines = [] - lines_kw = {'label':'_nolegend_'} + lines_kw = {'label': '_nolegend_'} if elinewidth: lines_kw['linewidth'] = elinewidth else: if 'linewidth' in kwargs: - lines_kw['linewidth']=kwargs['linewidth'] + lines_kw['linewidth'] = kwargs['linewidth'] if 'lw' in kwargs: - lines_kw['lw']=kwargs['lw'] + lines_kw['lw'] = kwargs['lw'] if 'transform' in kwargs: lines_kw['transform'] = kwargs['transform'] # arrays fine here, they are booleans and hence not units if not iterable(lolims): - lolims = np.asarray([lolims]*len(x), bool) - else: lolims = np.asarray(lolims, bool) + lolims = np.asarray([lolims] * len(x), bool) + else: + lolims = np.asarray(lolims, bool) - if not iterable(uplims): uplims = np.array([uplims]*len(x), bool) - else: uplims = np.asarray(uplims, bool) + if not iterable(uplims): + uplims = np.array([uplims] * len(x), bool) + else: + uplims = np.asarray(uplims, bool) - if not iterable(xlolims): xlolims = np.array([xlolims]*len(x), bool) - else: xlolims = np.asarray(xlolims, bool) + if not iterable(xlolims): + xlolims = np.array([xlolims] * len(x), bool) + else: + xlolims = np.asarray(xlolims, bool) - if not iterable(xuplims): xuplims = np.array([xuplims]*len(x), bool) - else: xuplims = np.asarray(xuplims, bool) + if not iterable(xuplims): + xuplims = np.array([xuplims] * len(x), bool) + else: + xuplims = np.asarray(xuplims, bool) everymask = np.arange(len(x)) % errorevery == 0 @@ -5464,17 +5495,16 @@ def xywhere(xs, ys, mask): return xs[mask], ys[mask] where mask is True but xs and ys are not arrays """ - assert len(xs)==len(ys) - assert len(xs)==len(mask) + assert len(xs) == len(ys) + assert len(xs) == len(mask) xs = [thisx for thisx, b in zip(xs, mask) if b] ys = [thisy for thisy, b in zip(ys, mask) if b] return xs, ys - if capsize > 0: plot_kw = { - 'ms':2*capsize, - 'label':'_nolegend_'} + 'ms': 2 * capsize, + 'label': '_nolegend_'} if capthick is not None: # 'mew' has higher priority, I believe, # if both 'mew' and 'markeredgewidth' exists. @@ -5485,30 +5515,30 @@ def xywhere(xs, ys, mask): # For backwards-compat, allow explicit setting of # 'mew' or 'markeredgewidth' to over-ride capthick. if 'markeredgewidth' in kwargs: - plot_kw['markeredgewidth']=kwargs['markeredgewidth'] + plot_kw['markeredgewidth'] = kwargs['markeredgewidth'] if 'mew' in kwargs: - plot_kw['mew']=kwargs['mew'] + plot_kw['mew'] = kwargs['mew'] if 'transform' in kwargs: plot_kw['transform'] = kwargs['transform'] if xerr is not None: - if (iterable(xerr) and len(xerr)==2 and - iterable(xerr[0]) and iterable(xerr[1])): + if (iterable(xerr) and len(xerr) == 2 and + iterable(xerr[0]) and iterable(xerr[1])): # using list comps rather than arrays to preserve units - left = [thisx-thiserr for (thisx, thiserr) - in cbook.safezip(x,xerr[0])] - right = [thisx+thiserr for (thisx, thiserr) - in cbook.safezip(x,xerr[1])] + left = [thisx - thiserr for (thisx, thiserr) + in cbook.safezip(x, xerr[0])] + right = [thisx + thiserr for (thisx, thiserr) + in cbook.safezip(x, xerr[1])] else: # using list comps rather than arrays to preserve units - left = [thisx-thiserr for (thisx, thiserr) - in cbook.safezip(x,xerr)] - right = [thisx+thiserr for (thisx, thiserr) - in cbook.safezip(x,xerr)] + left = [thisx - thiserr for (thisx, thiserr) + in cbook.safezip(x, xerr)] + right = [thisx + thiserr for (thisx, thiserr) + in cbook.safezip(x, xerr)] yo, _ = xywhere(y, right, everymask) - lo, ro= xywhere(left, right, everymask) - barcols.append( self.hlines(yo, lo, ro, **lines_kw ) ) + lo, ro = xywhere(left, right, everymask) + barcols.append(self.hlines(yo, lo, ro, **lines_kw)) if capsize > 0: if xlolims.any(): # can't use numpy logical indexing since left and @@ -5517,75 +5547,75 @@ def xywhere(xs, ys, mask): caplines.extend( self.plot(leftlo, ylo, ls='None', - marker=mlines.CARETLEFT, **plot_kw) ) + marker=mlines.CARETLEFT, **plot_kw)) xlolims = ~xlolims leftlo, ylo = xywhere(left, y, xlolims & everymask) - caplines.extend( self.plot(leftlo, ylo, 'k|', **plot_kw) ) + caplines.extend(self.plot(leftlo, ylo, 'k|', **plot_kw)) else: leftlo, ylo = xywhere(left, y, everymask) - caplines.extend( self.plot(leftlo, ylo, 'k|', **plot_kw) ) + caplines.extend(self.plot(leftlo, ylo, 'k|', **plot_kw)) if xuplims.any(): rightup, yup = xywhere(right, y, xuplims & everymask) caplines.extend( - self.plot(rightup, yup, ls='None', - marker=mlines.CARETRIGHT, **plot_kw) ) + self.plot(rightup, yup, ls='None', + marker=mlines.CARETRIGHT, **plot_kw)) xuplims = ~xuplims rightup, yup = xywhere(right, y, xuplims & everymask) - caplines.extend( self.plot(rightup, yup, 'k|', **plot_kw) ) + caplines.extend(self.plot(rightup, yup, 'k|', **plot_kw)) else: rightup, yup = xywhere(right, y, everymask) - caplines.extend( self.plot(rightup, yup, 'k|', **plot_kw) ) + caplines.extend(self.plot(rightup, yup, 'k|', **plot_kw)) if yerr is not None: - if (iterable(yerr) and len(yerr)==2 and - iterable(yerr[0]) and iterable(yerr[1])): + if (iterable(yerr) and len(yerr) == 2 and + 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])] - upper = [thisy+thiserr for (thisy, thiserr) - in cbook.safezip(y,yerr[1])] + lower = [thisy - thiserr for (thisy, thiserr) + in cbook.safezip(y, yerr[0])] + upper = [thisy + thiserr for (thisy, thiserr) + in cbook.safezip(y, yerr[1])] else: # using list comps rather than arrays to preserve units - lower = [thisy-thiserr for (thisy, thiserr) - in cbook.safezip(y,yerr)] - upper = [thisy+thiserr for (thisy, thiserr) - in cbook.safezip(y,yerr)] + lower = [thisy - thiserr for (thisy, thiserr) + in cbook.safezip(y, yerr)] + upper = [thisy + thiserr for (thisy, thiserr) + in cbook.safezip(y, yerr)] xo, _ = xywhere(x, lower, everymask) - lo, uo= xywhere(lower, upper, everymask) - barcols.append( self.vlines(xo, lo, uo, **lines_kw) ) + lo, uo = xywhere(lower, upper, everymask) + barcols.append(self.vlines(xo, lo, uo, **lines_kw)) if capsize > 0: if lolims.any(): xlo, lowerlo = xywhere(x, lower, lolims & everymask) caplines.extend( self.plot(xlo, lowerlo, ls='None', - marker=mlines.CARETDOWN, **plot_kw) ) + marker=mlines.CARETDOWN, **plot_kw)) lolims = ~lolims xlo, lowerlo = xywhere(x, lower, lolims & everymask) - caplines.extend( self.plot(xlo, lowerlo, 'k_', **plot_kw) ) + caplines.extend(self.plot(xlo, lowerlo, 'k_', **plot_kw)) else: xlo, lowerlo = xywhere(x, lower, everymask) - caplines.extend( self.plot(xlo, lowerlo, 'k_', **plot_kw) ) + caplines.extend(self.plot(xlo, lowerlo, 'k_', **plot_kw)) if uplims.any(): xup, upperup = xywhere(x, upper, uplims & everymask) caplines.extend( self.plot(xup, upperup, ls='None', - marker=mlines.CARETUP, **plot_kw) ) + marker=mlines.CARETUP, **plot_kw)) uplims = ~uplims xup, upperup = xywhere(x, upper, uplims & everymask) - caplines.extend( self.plot(xup, upperup, 'k_', **plot_kw) ) + caplines.extend(self.plot(xup, upperup, 'k_', **plot_kw)) else: xup, upperup = xywhere(x, upper, everymask) - caplines.extend( self.plot(xup, upperup, 'k_', **plot_kw) ) + caplines.extend(self.plot(xup, upperup, 'k_', **plot_kw)) if not barsabove and fmt is not None: - l0, = self.plot(x,y,fmt,**kwargs) + l0, = self.plot(x, y, fmt, **kwargs) if ecolor is None: if l0 is None: @@ -5601,13 +5631,14 @@ def xywhere(xs, ys, mask): self.autoscale_view() self._hold = holdstate - errorbar_container = ErrorbarContainer((l0, tuple(caplines), tuple(barcols)), - has_xerr=(xerr is not None), - has_yerr=(yerr is not None), - label=label) + errorbar_container = ErrorbarContainer( + (l0, tuple(caplines), tuple(barcols)), + has_xerr=(xerr is not None), + has_yerr=(yerr is not None), + label=label) self.containers.append(errorbar_container) - return errorbar_container # (l0, caplines, barcols) + return errorbar_container # (l0, caplines, barcols) def boxplot(self, x, notch=False, sym='b+', vert=True, whis=1.5, positions=None, widths=None, patch_artist=False, @@ -5708,10 +5739,10 @@ def boxplot(self, x, notch=False, sym='b+', vert=True, whis=1.5, def bootstrapMedian(data, N=5000): # determine 95% confidence intervals of the median M = len(data) - percentile = [2.5,97.5] + percentile = [2.5, 97.5] estimate = np.zeros(N) for n in range(N): - bsIndex = np.random.random_integers(0,M-1,M) + bsIndex = np.random.random_integers(0, M - 1, M) bsData = data[bsIndex] estimate[n] = mlab.prctile(bsData, 50) CI = mlab.prctile(estimate, percentile) @@ -5732,11 +5763,12 @@ def computeConfInterval(data, med, iq, bootstrap): # and Larsen, W.A. (1978) "Variations of # Boxplots", The American Statistician, 32:12-16. N = len(data) - notch_min = med - 1.57*iq/np.sqrt(N) - notch_max = med + 1.57*iq/np.sqrt(N) + notch_min = med - 1.57 * iq / np.sqrt(N) + notch_max = med + 1.57 * iq / np.sqrt(N) return notch_min, notch_max - if not self._hold: self.cla() + if not self._hold: + self.cla() holdStatus = self._hold whiskers, caps, boxes, medians, fliers = [], [], [], [], [] @@ -5746,7 +5778,7 @@ def computeConfInterval(data, med, iq, bootstrap): if hasattr(x[0], 'shape'): x = list(x) else: - x = [x,] + x = [x, ] elif len(x.shape) == 2: nr, nc = x.shape if nr == 1: @@ -5754,7 +5786,7 @@ def computeConfInterval(data, med, iq, bootstrap): elif nc == 1: x = [x.ravel()] else: - x = [x[:,i] for i in xrange(nc)] + x = [x[:, i] for i in xrange(nc)] else: raise ValueError("input x can have no more than 2 dimensions") if not hasattr(x[0], '__len__'): @@ -5792,13 +5824,12 @@ def computeConfInterval(data, med, iq, bootstrap): if ci is not None and len(ci) != 2: raise ValueError(msg3) - # get some plot info if positions is None: positions = range(1, col + 1) if widths is None: distance = max(positions) - min(positions) - widths = min(0.15*max(distance,1.0), 0.5) + widths = min(0.15 * max(distance, 1.0), 0.5) if isinstance(widths, float) or isinstance(widths, int): widths = np.ones((col,), float) * widths @@ -5807,12 +5838,12 @@ def computeConfInterval(data, med, iq, bootstrap): for i, pos in enumerate(positions): d = np.ravel(x[i]) row = len(d) - if row==0: + if row == 0: # no data, skip this position continue # get median and quartiles - q1, med, q3 = mlab.prctile(d,[25,50,75]) + q1, med, q3 = mlab.prctile(d, [25, 50, 75]) # replace with input medians if available if usermedians is not None: @@ -5821,15 +5852,15 @@ def computeConfInterval(data, med, iq, bootstrap): # get high extreme iq = q3 - q1 - hi_val = q3 + whis*iq - wisk_hi = np.compress( d <= hi_val , d ) + hi_val = q3 + whis * iq + wisk_hi = np.compress(d <= hi_val, d) if len(wisk_hi) == 0: wisk_hi = q3 else: wisk_hi = max(wisk_hi) # get low extreme - lo_val = q1 - whis*iq - wisk_lo = np.compress( d >= lo_val, d ) + lo_val = q1 - whis * iq + wisk_lo = np.compress(d >= lo_val, d) if len(wisk_lo) == 0: wisk_lo = q1 else: @@ -5840,8 +5871,8 @@ def computeConfInterval(data, med, iq, bootstrap): flier_hi_x = [] flier_lo_x = [] if len(sym) != 0: - flier_hi = np.compress( d > wisk_hi, d ) - flier_lo = np.compress( d < wisk_lo, d ) + flier_hi = np.compress(d > wisk_hi, d) + flier_lo = np.compress(d < wisk_lo, d) flier_hi_x = np.ones(flier_hi.shape[0]) * pos flier_lo_x = np.ones(flier_lo.shape[0]) * pos @@ -5871,7 +5902,7 @@ def computeConfInterval(data, med, iq, bootstrap): # make our notched box vectors box_x = [box_x_min, box_x_max, box_x_max, cap_x_max, box_x_max, box_x_max, box_x_min, box_x_min, cap_x_min, box_x_min, - box_x_min ] + box_x_min] box_y = [q1, q1, notch_min, med, notch_max, q3, q3, notch_max, med, notch_min, q1] # make our median line vectors @@ -5880,26 +5911,27 @@ def computeConfInterval(data, med, iq, bootstrap): # calculate 'regular' plot else: # make our box vectors - box_x = [box_x_min, box_x_max, box_x_max, box_x_min, box_x_min ] - box_y = [q1, q1, q3, q3, q1 ] + box_x = [box_x_min, box_x_max, box_x_max, + box_x_min, box_x_min] + box_y = [q1, q1, q3, q3, q1] # make our median line vectors med_x = [box_x_min, box_x_max] - def to_vc(xs,ys): + def to_vc(xs, ys): # convert arguments to verts and codes verts = [] #codes = [] - for xi,yi in zip(xs,ys): - verts.append( (xi,yi) ) - verts.append( (0,0) ) # ignored + for xi, yi in zip(xs, ys): + verts.append((xi, yi)) + verts.append((0, 0)) # ignored codes = [mpath.Path.MOVETO] + \ - [mpath.Path.LINETO]*(len(verts)-2) + \ + [mpath.Path.LINETO] * (len(verts) - 2) + \ [mpath.Path.CLOSEPOLY] - return verts,codes + return verts, codes - def patch_list(xs,ys): - verts,codes = to_vc(xs,ys) - path = mpath.Path( verts, codes ) + def patch_list(xs, ys): + verts, codes = to_vc(xs, ys) + path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path) self.add_artist(patch) return [patch] @@ -5908,17 +5940,19 @@ def patch_list(xs,ys): if vert: def doplot(*args): return self.plot(*args) - def dopatch(xs,ys): - return patch_list(xs,ys) + + def dopatch(xs, ys): + return patch_list(xs, ys) else: def doplot(*args): shuffled = [] for i in xrange(0, len(args), 3): - shuffled.extend([args[i+1], args[i], args[i+2]]) + shuffled.extend([args[i + 1], args[i], args[i + 2]]) return self.plot(*shuffled) - def dopatch(xs,ys): - xs,ys = ys,xs # flip X, Y - return patch_list(xs,ys) + + def dopatch(xs, ys): + xs, ys = ys, xs # flip X, Y + return patch_list(xs, ys) if patch_artist: median_color = 'k' @@ -5934,7 +5968,7 @@ def dopatch(xs,ys): else: boxes.extend(doplot(box_x, box_y, 'b-')) - medians.extend(doplot(med_x, med_y, median_color+'-')) + medians.extend(doplot(med_x, med_y, median_color + '-')) fliers.extend(doplot(flier_hi_x, flier_hi, sym, flier_lo_x, flier_lo, sym)) @@ -5944,7 +5978,7 @@ def dopatch(xs,ys): else: setticks, setlim = self.set_yticks, self.set_ylim - newlimits = min(positions)-0.5, max(positions)+0.5 + newlimits = min(positions) - 0.5, max(positions) + 0.5 setlim(newlimits) setticks(positions) @@ -5956,9 +5990,9 @@ def dopatch(xs,ys): @docstring.dedent_interpd def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, - vmin=None, vmax=None, alpha=None, linewidths=None, - faceted=True, verts=None, - **kwargs): + vmin=None, vmax=None, alpha=None, linewidths=None, + faceted=True, verts=None, + **kwargs): """ Make a scatter plot. @@ -6045,7 +6079,8 @@ def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, returned. """ - if not self._hold: self.cla() + if not self._hold: + self.cla() self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs) x = self.convert_xunits(x) @@ -6080,14 +6115,13 @@ def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, else: colors = mcolors.colorConverter.to_rgba_array(c, alpha) - if faceted: edgecolors = None else: edgecolors = 'none' warnings.warn( '''replace "faceted=False" with "edgecolors='none'"''', - DeprecationWarning) #2008/04/18 + DeprecationWarning) # 2008/04/18 sym = None symstyle = 0 @@ -6104,19 +6138,20 @@ def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, edgecolors = 'face' collection = mcoll.PathCollection( - (path,), scales, - facecolors = colors, - edgecolors = edgecolors, - linewidths = linewidths, - offsets = zip(x,y), - transOffset = kwargs.pop('transform', self.transData), - ) + (path,), scales, + facecolors=colors, + edgecolors=edgecolors, + linewidths=linewidths, + offsets=zip(x, y), + transOffset=kwargs.pop('transform', self.transData), + ) collection.set_transform(mtransforms.IdentityTransform()) collection.set_alpha(alpha) collection.update(kwargs) if colors is None: - if norm is not None: assert(isinstance(norm, mcolors.Normalize)) + if norm is not None: + assert(isinstance(norm, mcolors.Normalize)) collection.set_array(np.asarray(c)) collection.set_cmap(cmap) collection.set_norm(norm) @@ -6131,10 +6166,10 @@ def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, # to data coords to get the exact bounding box for efficiency # reasons. It can be done right if this is deemed important. # Also, only bother with this padding if there is anything to draw. - if self._xmargin < 0.05 and x.size > 0 : + if self._xmargin < 0.05 and x.size > 0: self.set_xmargin(0.05) - if self._ymargin < 0.05 and x.size > 0 : + if self._ymargin < 0.05 and x.size > 0: self.set_ymargin(0.05) self.add_collection(collection) @@ -6143,12 +6178,12 @@ def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, return collection @docstring.dedent_interpd - def hexbin(self, x, y, C = None, gridsize = 100, bins = None, - xscale = 'linear', yscale = 'linear', extent = None, - cmap=None, norm=None, vmin=None, vmax=None, - alpha=None, linewidths=None, edgecolors='none', - reduce_C_function = np.mean, mincnt=None, marginals=False, - **kwargs): + def hexbin(self, x, y, C=None, gridsize=100, bins=None, + xscale='linear', yscale='linear', extent=None, + cmap=None, norm=None, vmin=None, vmax=None, + alpha=None, linewidths=None, edgecolors='none', + reduce_C_function=np.mean, mincnt=None, marginals=False, + **kwargs): """ Make a hexagonal binning plot. @@ -6277,29 +6312,28 @@ def hexbin(self, x, y, C = None, gridsize = 100, bins = None, """ - if not self._hold: self.cla() + if not self._hold: + self.cla() self._process_unit_info(xdata=x, ydata=y, kwargs=kwargs) - x, y, C = cbook.delete_masked_points(x, y, C) - # Set the size of the hexagon grid if iterable(gridsize): nx, ny = gridsize else: nx = gridsize - ny = int(nx/math.sqrt(3)) + ny = int(nx / math.sqrt(3)) # Count the number of data in each hexagon x = np.array(x, float) y = np.array(y, float) - if xscale=='log': + if xscale == 'log': if np.any(x <= 0.0): raise ValueError("x contains non-positive values, so can not" " be log-scaled") x = np.log10(x) - if yscale=='log': + if yscale == 'log': if np.any(y <= 0.0): raise ValueError("y contains non-positive values, so can not" " be log-scaled") @@ -6316,15 +6350,15 @@ def hexbin(self, x, y, C = None, gridsize = 100, bins = None, padding = 1.e-9 * (xmax - xmin) xmin -= padding xmax += padding - sx = (xmax-xmin) / nx - sy = (ymax-ymin) / ny + sx = (xmax - xmin) / nx + sy = (ymax - ymin) / ny if marginals: xorig = x.copy() yorig = y.copy() - x = (x-xmin)/sx - y = (y-ymin)/sy + x = (x - xmin) / sx + y = (y - ymin) / sy ix1 = np.round(x).astype(int) iy1 = np.round(y).astype(int) ix2 = np.floor(x).astype(int) @@ -6334,39 +6368,39 @@ def hexbin(self, x, y, C = None, gridsize = 100, bins = None, ny1 = ny + 1 nx2 = nx ny2 = ny - n = nx1*ny1+nx2*ny2 + n = nx1 * ny1 + nx2 * ny2 - d1 = (x-ix1)**2 + 3.0 * (y-iy1)**2 - d2 = (x-ix2-0.5)**2 + 3.0 * (y-iy2-0.5)**2 - bdist = (d1= 0) and (ix1[i] < nx1) and - (iy1[i] >= 0) and (iy1[i] < ny1)): - lattice1[ix1[i], iy1[i]]+=1 + (iy1[i] >= 0) and (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)): - lattice2[ix2[i], iy2[i]]+=1 + (iy2[i] >= 0) and (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]= 0) and (ix1[i] < nx1) and - (iy1[i] >= 0) and (iy1[i] < ny1)): - lattice1[ix1[i], iy1[i]].append( C[i] ) + (iy1[i] >= 0) and (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)): - lattice2[ix2[i], iy2[i]].append( C[i] ) - + (iy2[i] >= 0) and (iy2[i] < ny2)): + lattice2[ix2[i], iy2[i]].append(C[i]) for i in xrange(nx1): for j in xrange(ny1): - vals = lattice1[i,j] - if len(vals)>mincnt: - lattice1[i,j] = reduce_C_function( vals ) + vals = lattice1[i, j] + if len(vals) > mincnt: + lattice1[i, j] = reduce_C_function(vals) else: - lattice1[i,j] = np.nan + lattice1[i, j] = np.nan for i in xrange(nx2): for j in xrange(ny2): - vals = lattice2[i,j] - if len(vals)>mincnt: - lattice2[i,j] = reduce_C_function( vals ) + vals = lattice2[i, j] + if len(vals) > mincnt: + lattice2[i, j] = reduce_C_function(vals) else: - lattice2[i,j] = np.nan + lattice2[i, j] = np.nan accum = np.hstack(( lattice1.astype(float).ravel(), lattice2.astype(float).ravel())) good_idxs = ~np.isnan(accum) offsets = np.zeros((n, 2), float) - offsets[:nx1*ny1,0] = np.repeat(np.arange(nx1), ny1) - offsets[:nx1*ny1,1] = np.tile(np.arange(ny1), nx1) - offsets[nx1*ny1:,0] = np.repeat(np.arange(nx2) + 0.5, ny2) - offsets[nx1*ny1:,1] = np.tile(np.arange(ny2), nx2) + 0.5 - offsets[:,0] *= sx - offsets[:,1] *= sy - offsets[:,0] += xmin - offsets[:,1] += ymin + offsets[:nx1 * ny1, 0] = np.repeat(np.arange(nx1), ny1) + offsets[:nx1 * ny1, 1] = np.tile(np.arange(ny1), nx1) + offsets[nx1 * ny1:, 0] = np.repeat(np.arange(nx2) + 0.5, ny2) + offsets[nx1 * ny1:, 1] = np.tile(np.arange(ny2), nx2) + 0.5 + offsets[:, 0] *= sx + offsets[:, 1] *= sy + offsets[:, 0] += xmin + offsets[:, 1] += ymin # remove accumulation bins with no data - offsets = offsets[good_idxs,:] + offsets = offsets[good_idxs, :] accum = accum[good_idxs] - if xscale=='log': - offsets[:,0] = 10**(offsets[:,0]) - xmin = 10**xmin - xmax = 10**xmax + if xscale == 'log': + offsets[:, 0] = 10 ** (offsets[:, 0]) + xmin = 10 ** xmin + xmax = 10 ** xmax self.set_xscale('log') - if yscale=='log': - offsets[:,1] = 10**(offsets[:,1]) - ymin = 10**ymin - ymax = 10**ymax + if yscale == 'log': + offsets[:, 1] = 10 ** (offsets[:, 1]) + ymin = 10 ** ymin + ymax = 10 ** ymax self.set_yscale('log') polygon = np.zeros((6, 2), float) - polygon[:,0] = sx * np.array([ 0.5, 0.5, 0.0, -0.5, -0.5, 0.0]) - polygon[:,1] = sy * np.array([-0.5, 0.5, 1.0, 0.5, -0.5, -1.0]) / 3.0 + polygon[:, 0] = sx * np.array([0.5, 0.5, 0.0, -0.5, -0.5, 0.0]) + polygon[:, 1] = sy * np.array([-0.5, 0.5, 1.0, 0.5, -0.5, -1.0]) / 3.0 - if edgecolors=='none': + if edgecolors == 'none': edgecolors = 'face' collection = mcoll.PolyCollection( [polygon], - edgecolors = edgecolors, - linewidths = linewidths, - offsets = offsets, - transOffset = mtransforms.IdentityTransform(), - offset_position = "data" - ) + edgecolors=edgecolors, + linewidths=linewidths, + offsets=offsets, + transOffset=mtransforms.IdentityTransform(), + offset_position="data" + ) if isinstance(norm, mcolors.LogNorm): - if (accum==0).any(): + if (accum == 0).any(): # make sure we have not zeros accum += 1 @@ -6467,17 +6500,18 @@ def hexbin(self, x, y, C = None, gridsize = 100, bins = None, norm.autoscale(accum) # Transform accum if needed - if bins=='log': - accum = np.log10(accum+1) - elif bins!=None: + if bins == 'log': + accum = np.log10(accum + 1) + elif bins is not None: if not iterable(bins): minimum, maximum = min(accum), max(accum) - bins-=1 # one less edge than bins - bins = minimum + (maximum-minimum)*np.arange(bins)/bins + bins -= 1 # one less edge than bins + bins = minimum + (maximum - minimum) * np.arange(bins) / bins bins = np.sort(bins) accum = bins.searchsorted(accum) - if norm is not None: assert(isinstance(norm, mcolors.Normalize)) + if norm is not None: + assert(isinstance(norm, mcolors.Normalize)) collection.set_array(accum) collection.set_cmap(cmap) collection.set_norm(norm) @@ -6490,7 +6524,7 @@ def hexbin(self, x, y, C = None, gridsize = 100, bins = None, collection.autoscale_None() corners = ((xmin, ymin), (xmax, ymax)) - self.update_datalim( corners) + self.update_datalim(corners) self.autoscale_view(tight=True) # add the collection last @@ -6498,15 +6532,14 @@ def hexbin(self, x, y, C = None, gridsize = 100, bins = None, if not marginals: return collection - if C is None: C = np.ones(len(x)) def coarse_bin(x, y, coarse): - ind = coarse.searchsorted(x).clip(0, len(coarse)-1) + ind = coarse.searchsorted(x).clip(0, len(coarse) - 1) mus = np.zeros(len(coarse)) for i in range(len(coarse)): - mu = reduce_C_function(y[ind==i]) + mu = reduce_C_function(y[ind == i]) mus[i] = mu return mus @@ -6515,23 +6548,24 @@ def coarse_bin(x, y, coarse): xcoarse = coarse_bin(xorig, C, coarse) valid = ~np.isnan(xcoarse) verts, values = [], [] - for i,val in enumerate(xcoarse): + for i, val in enumerate(xcoarse): thismin = coarse[i] - if i= 1.5. hist_kwargs = dict(range=bin_range) - if np.__version__ < "1.3": # version 1.1 and 1.2 + if np.__version__ < "1.3": # version 1.1 and 1.2 hist_kwargs['new'] = True n = [] @@ -8100,7 +8146,7 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, # so that each histogram uses the same bins m, bins = np.histogram(x[i], bins, weights=w[i], **hist_kwargs) if mlast is None: - mlast = np.zeros(len(bins)-1, m.dtype) + mlast = np.zeros(len(bins) - 1, m.dtype) if normed: db = np.diff(bins) m = (m.astype(float) / db) / m.sum() @@ -8112,14 +8158,14 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, if cumulative: slc = slice(None) if cbook.is_numlike(cumulative) and cumulative < 0: - slc = slice(None,None,-1) + slc = slice(None, None, -1) if normed: n = [(m * np.diff(bins))[slc].cumsum()[slc] for m in n] else: n = [m[slc].cumsum()[slc] for m in n] - n.reverse() # put them back in the right order + n.reverse() # put them back in the right order patches = [] @@ -8128,26 +8174,26 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, if rwidth is not None: dr = min(1.0, max(0.0, rwidth)) - elif len(n)>1: + elif len(n) > 1: dr = 0.8 else: dr = 1.0 - if histtype=='bar' and not stacked: - width = dr*totwidth/nx + if histtype == 'bar' and not stacked: + width = dr * totwidth / nx dw = width if nx > 1: - boffset = -0.5*dr*totwidth*(1.0-1.0/nx) + boffset = -0.5 * dr * totwidth * (1.0 - 1.0 / nx) else: boffset = 0.0 stacked = False - elif histtype=='barstacked' or stacked: - width = dr*totwidth + elif histtype == 'barstacked' or stacked: + width = dr * totwidth boffset, dw = 0.0, 0.0 if align == 'mid' or align == 'edge': - boffset += 0.5*totwidth + boffset += 0.5 * totwidth elif align == 'right': boffset += totwidth @@ -8157,27 +8203,27 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, _barfunc = self.bar for m, c in zip(n, color): - patch = _barfunc(bins[:-1]+boffset, m, width, + patch = _barfunc(bins[:-1] + boffset, m, width, align='center', log=log, color=c) patches.append(patch) boffset += dw elif histtype.startswith('step'): - x = np.zeros( 2*len(bins), np.float ) - y = np.zeros( 2*len(bins), np.float ) + x = np.zeros(2 * len(bins), np.float) + y = np.zeros(2 * len(bins), np.float) x[0::2], x[1::2] = bins, bins minimum = np.min(n) if align == 'left' or align == 'center': - x -= 0.5*(bins[1]-bins[0]) + x -= 0.5 * (bins[1] - bins[0]) elif align == 'right': - x += 0.5*(bins[1]-bins[0]) + x += 0.5 * (bins[1] - bins[0]) if log: - y[0],y[-1] = minimum, minimum + y[0], y[-1] = minimum, minimum if orientation == 'horizontal': self.set_xscale('log') else: # orientation == 'vertical' @@ -8190,32 +8236,32 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, for m, c in zip(n, color): y[1:-1:2], y[2::2] = m, m if log: - y[ycmax]=None + if cmin is not None: + h[h < cmin] = None + if cmax is not None: + h[h > cmax] = None - pc = self.pcolorfast(xedges,yedges,h.T,**kwargs) - self.set_xlim(xedges[0],xedges[-1]) - self.set_ylim(yedges[0],yedges[-1]) + pc = self.pcolorfast(xedges, yedges, h.T, **kwargs) + self.set_xlim(xedges[0], xedges[-1]) + self.set_ylim(yedges[0], yedges[-1]) - return h,xedges,yedges,pc + return h, xedges, yedges, pc @docstring.dedent_interpd def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, @@ -8396,7 +8448,8 @@ def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, .. plot:: mpl_examples/pylab_examples/psd_demo.py """ - if not self._hold: self.cla() + if not self._hold: + self.cla() pxx, freqs = mlab.psd(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) pxx.shape = len(freqs), @@ -8407,17 +8460,18 @@ def psd(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, else: psd_units = 'dB' - self.plot(freqs, 10*np.log10(pxx), **kwargs) + self.plot(freqs, 10 * np.log10(pxx), **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Power Spectral Density (%s)' % psd_units) self.grid(True) vmin, vmax = self.viewLim.intervaly - intv = vmax-vmin + intv = vmax - vmin logi = int(np.log10(intv)) - if logi==0: logi=.1 - step = 10*logi + if logi == 0: + logi = .1 + step = 10 * logi #print vmin, vmax, step, intv, math.floor(vmin), math.ceil(vmax)+1 - ticks = np.arange(math.floor(vmin), math.ceil(vmax)+1, step) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) self.set_yticks(ticks) return pxx, freqs @@ -8476,23 +8530,24 @@ def csd(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, :meth:`psd` For a description of the optional parameters. """ - if not self._hold: self.cla() + if not self._hold: + self.cla() pxy, freqs = mlab.csd(x, y, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) pxy.shape = len(freqs), # pxy is complex freqs += Fc - self.plot(freqs, 10*np.log10(np.absolute(pxy)), **kwargs) + self.plot(freqs, 10 * np.log10(np.absolute(pxy)), **kwargs) self.set_xlabel('Frequency') self.set_ylabel('Cross Spectrum Magnitude (dB)') self.grid(True) vmin, vmax = self.viewLim.intervaly - intv = vmax-vmin - step = 10*int(np.log10(intv)) + intv = vmax - vmin + step = 10 * int(np.log10(intv)) - ticks = np.arange(math.floor(vmin), math.ceil(vmax)+1, step) + ticks = np.arange(math.floor(vmin), math.ceil(vmax) + 1, step) self.set_yticks(ticks) return pxy, freqs @@ -8548,7 +8603,8 @@ def cohere(self, x, y, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, .. plot:: mpl_examples/pylab_examples/cohere_demo.py """ - if not self._hold: self.cla() + if not self._hold: + self.cla() cxy, freqs = mlab.cohere(x, y, NFFT, Fs, detrend, window, noverlap, scale_by_freq) freqs += Fc @@ -8623,7 +8679,8 @@ def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, .. plot:: mpl_examples/pylab_examples/specgram_demo.py """ - if not self._hold: self.cla() + if not self._hold: + self.cla() Pxx, freqs, bins = mlab.specgram(x, NFFT, Fs, detrend, window, noverlap, pad_to, sides, scale_by_freq) @@ -8631,7 +8688,8 @@ def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, Z = 10. * np.log10(Pxx) Z = np.flipud(Z) - if xextent is None: xextent = 0, np.amax(bins) + if xextent is None: + xextent = 0, np.amax(bins) xmin, xmax = xextent freqs += Fc extent = xmin, xmax, freqs[0], freqs[-1] @@ -8641,7 +8699,7 @@ def specgram(self, x, NFFT=256, Fs=2, Fc=0, detrend=mlab.detrend_none, return Pxx, freqs, bins, im def spy(self, Z, precision=0, marker=None, markersize=None, - aspect='equal', **kwargs): + aspect='equal', **kwargs): """ Plot the sparsity pattern on a 2-D array. @@ -8722,13 +8780,13 @@ 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.absolute(Z) > precision if 'cmap' not in kwargs: kwargs['cmap'] = mcolors.ListedColormap(['w', 'k'], name='binary') nr, nc = Z.shape - extent = [-0.5, nc-0.5, nr-0.5, -0.5] + extent = [-0.5, nc - 0.5, nr - 0.5, -0.5] ret = self.imshow(mask, interpolation='nearest', aspect=aspect, extent=extent, origin='upper', **kwargs) else: @@ -8743,16 +8801,18 @@ def spy(self, Z, precision=0, marker=None, markersize=None, x = c.col[nonzero] else: Z = np.asarray(Z) - nonzero = np.absolute(Z)>precision + nonzero = np.absolute(Z) > precision y, x = np.nonzero(nonzero) - if marker is None: marker = 's' - if markersize is None: markersize = 10 + if marker is None: + marker = 's' + if markersize is None: + markersize = 10 marks = mlines.Line2D(x, y, linestyle='None', marker=marker, markersize=markersize, **kwargs) self.add_line(marks) nr, nc = Z.shape - self.set_xlim(xmin=-0.5, xmax=nc-0.5) - self.set_ylim(ymin=nr-0.5, ymax=-0.5) + self.set_xlim(xmin=-0.5, xmax=nc - 0.5) + self.set_ylim(ymin=nr - 0.5, ymax=-0.5) self.set_aspect(aspect) ret = marks self.title.set_y(1.05) @@ -8812,7 +8872,6 @@ def get_default_bbox_extra_artists(self): bbox_extra_artists.append(t) return bbox_extra_artists - def get_tightbbox(self, renderer, call_axes_locator=True): """ Return the tight bounding box of the axes. @@ -8844,12 +8903,15 @@ def get_tightbbox(self, renderer, call_axes_locator=True): bb.append(self.title.get_window_extent(renderer)) bb_xaxis = self.xaxis.get_tightbbox(renderer) - if bb_xaxis: bb.append(bb_xaxis) + if bb_xaxis: + bb.append(bb_xaxis) bb_yaxis = self.yaxis.get_tightbbox(renderer) - if bb_yaxis: bb.append(bb_yaxis) + if bb_yaxis: + bb.append(bb_yaxis) - _bbox = mtransforms.Bbox.union([b for b in bb if b.width!=0 or b.height!=0]) + _bbox = mtransforms.Bbox.union( + [b for b in bb if b.width != 0 or b.height != 0]) return _bbox @@ -8886,6 +8948,7 @@ def triplot(self, *args, **kwargs): from matplotlib.gridspec import GridSpec, SubplotSpec + class SubplotBase: """ Base class for subplots, which are :class:`Axes` instances with @@ -8920,17 +8983,17 @@ def __init__(self, fig, *args, **kwargs): except ValueError: raise ValueError( 'Single argument to subplot must be a 3-digit integer') - self._subplotspec = GridSpec(rows, cols)[num-1] + self._subplotspec = GridSpec(rows, cols)[num - 1] # num - 1 for converting from MATLAB to python indexing - elif len(args)==3: + elif len(args) == 3: rows, cols, num = args rows = int(rows) cols = int(cols) if isinstance(num, tuple) and len(num) == 2: num = [int(n) for n in num] - self._subplotspec = GridSpec(rows, cols)[num[0]-1:num[1]] + self._subplotspec = GridSpec(rows, cols)[num[0] - 1:num[1]] else: - self._subplotspec = GridSpec(rows, cols)[int(num)-1] + self._subplotspec = GridSpec(rows, cols)[int(num) - 1] # num - 1 for converting from MATLAB to python indexing else: raise ValueError('Illegal argument(s) to subplot: %s' % (args,)) @@ -8953,12 +9016,12 @@ def __reduce__(self): def get_geometry(self): """get the subplot geometry, eg 2,2,3""" rows, cols, num1, num2 = self.get_subplotspec().get_geometry() - return rows, cols, num1+1 # for compatibility + return rows, cols, num1 + 1 # for compatibility # COVERAGE NOTE: Never used internally or from examples def change_geometry(self, numrows, numcols, num): """change subplot geometry, eg. from 1,1,1 to 2,2,3""" - self._subplotspec = GridSpec(numrows, numcols)[num-1] + self._subplotspec = GridSpec(numrows, numcols)[num - 1] self.update_params() self.set_position(self.figbox) @@ -8977,19 +9040,17 @@ def update_params(self): self.get_subplotspec().get_position(self.figure, return_all=True) - def is_first_col(self): - return self.colNum==0 + return self.colNum == 0 def is_first_row(self): - return self.rowNum==0 + return self.rowNum == 0 def is_last_row(self): - return self.rowNum==self.numRows-1 - + return self.rowNum == self.numRows - 1 def is_last_col(self): - return self.colNum==self.numCols-1 + return self.colNum == self.numCols - 1 # COVERAGE NOTE: Never used internally or from examples def label_outer(self): @@ -9006,7 +9067,6 @@ def label_outer(self): for label in self.get_yticklabels(): label.set_visible(firstcol) - def _make_twin_axes(self, *kl, **kwargs): """ make a twinx axes of self. This is used for twinx and twiny. @@ -9016,6 +9076,8 @@ def _make_twin_axes(self, *kl, **kwargs): _subplot_classes = {} + + def subplot_class_factory(axes_class=None): # This makes a new class that inherits from SubplotBase and the # given axes_class (which is assumed to be a subclass of Axes). From c56826e830cd96325db775be7dbe8d7d5b4b43b3 Mon Sep 17 00:00:00 2001 From: Nelle Varoquaux Date: Sun, 14 Oct 2012 12:08:07 +0200 Subject: [PATCH 2/2] PEP8 fixes on axes.py --- lib/matplotlib/axes.py | 171 ++++++++++++++++++++++------------------- 1 file changed, 93 insertions(+), 78 deletions(-) diff --git a/lib/matplotlib/axes.py b/lib/matplotlib/axes.py index 9bdd427fc1fa..fc9140348a29 100644 --- a/lib/matplotlib/axes.py +++ b/lib/matplotlib/axes.py @@ -1,8 +1,6 @@ from __future__ import division, print_function import math -import sys import warnings -import datetime from operator import itemgetter import itertools @@ -428,7 +426,8 @@ def __init__(self, fig, rect, *yticklabels* sequence of strings *yticks* sequence of floats ================ ========================================= - """ % {'scale': ' | '.join([repr(x) for x in mscale.get_scale_names()])} + """ % {'scale': ' | '.join([repr(x) + for x in mscale.get_scale_names()])} martist.Artist.__init__(self) if isinstance(rect, mtransforms.Bbox): self._position = rect @@ -519,7 +518,7 @@ def get_window_extent(self, *args, **kwargs): return self.bbox def _init_axis(self): - "move this out of __init__ because non-separable axes don't use it" + """move this out of __init__ because non-separable axes don't use it""" self.xaxis = maxis.XAxis(self) self.spines['bottom'].register_axis(self.xaxis) self.spines['top'].register_axis(self.xaxis) @@ -752,7 +751,7 @@ def _update_transScale(self): pass def get_position(self, original=False): - 'Return the a copy of the axes rectangle as a Bbox' + """Return the a copy of the axes rectangle as a Bbox""" if original: return self._originalPosition.frozen() else: @@ -800,8 +799,8 @@ def set_axes_locator(self, locator): """ set axes_locator - ACCEPT : a callable object which takes an axes instance and renderer and - returns a bbox. + ACCEPT : a callable object which takes an axes instance and renderer + and returns a bbox. """ self._axes_locator = locator @@ -972,10 +971,6 @@ def cla(self): self._shared_x_axes.clean() self._shared_y_axes.clean() - def get_frame(self): - raise AttributeError('Axes.frame was removed in favor of Axes.spines') - frame = property(get_frame) - def clear(self): """clear the axes""" self.cla() @@ -1190,7 +1185,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': @@ -1252,7 +1247,8 @@ 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 @@ -1383,8 +1379,11 @@ def get_frame(self): warnings.warn('use ax.patch instead', DeprecationWarning) return self.patch + frame = property(get_frame) + def get_legend(self): - """Return the legend.Legend instance, or None if no legend is defined""" + """Return the legend.Legend instance, or None if no legend is defined. + """ return self.legend_ def get_images(self): @@ -1413,11 +1412,13 @@ def get_yaxis(self): def get_ygridlines(self): """Get the y grid lines as a list of Line2D instances""" - return cbook.silent_list('Line2D ygridline', self.yaxis.get_gridlines()) + return cbook.silent_list('Line2D ygridline', + self.yaxis.get_gridlines()) def get_yticklines(self): """Get the ytick lines as a list of Line2D instances""" - return cbook.silent_list('Line2D ytickline', self.yaxis.get_ticklines()) + return cbook.silent_list('Line2D ytickline', + self.yaxis.get_ticklines()) #### Adding and tracking artists @@ -1510,7 +1511,10 @@ def add_line(self, line): return line def _update_line_limits(self, line): - """Figures out the data limit of the given line, updating self.dataLim.""" + """ + Figures out the data limit of the given line, updating + self.dataLim. + """ path = line.get_path() if path.vertices.size == 0: return @@ -2139,7 +2143,8 @@ def get_axisbelow(self): def set_axisbelow(self, b): """ - Set whether the axis ticks and gridlines are above or below most artists + Set whether the axis ticks and gridlines are above or below most + artists ACCEPTS: [ *True* | *False* ] """ @@ -2158,14 +2163,14 @@ def grid(self, b=None, which='major', axis='both', **kwargs): compatibility, *b* may also be a string, 'on' or 'off'.) If *b* is *None* and ``len(kwargs)==0``, toggle the grid state. If - *kwargs* are supplied, it is assumed that you want a grid and *b* - is thus set to *True*. + *kwargs* are supplied, it is assumed that you want a grid and *b* is + thus set to *True*. *which* can be 'major' (default), 'minor', or 'both' to control whether major tick grids, minor tick grids, or both are affected. - *axis* can be 'both' (default), 'x', or 'y' to control which - set of gridlines are drawn. + *axis* can be 'both' (default), 'x', or 'y' to control which set of + gridlines are drawn. *kwargs* are used to set the grid line properties, eg:: @@ -3020,6 +3025,7 @@ def drag_pan(self, button, key, x, y): Intended to be overridden by new projection types. """ + def format_deltas(key, dx, dy): if key == 'control': if(abs(dx) > abs(dy)): @@ -3429,7 +3435,7 @@ def text(self, x, y, s, fontdict=None, self.texts.append(t) t._remove_method = lambda h: self.texts.remove(h) - #if t.get_clip_on(): t.set_clip_box(self.bbox) + # if t.get_clip_on(): t.set_clip_box(self.bbox) if 'clip_on' in kwargs: t.set_clip_box(self.bbox) return t @@ -4025,7 +4031,6 @@ def plot_date(self, x, y, fmt='bo', tz=None, xdate=True, ydate=False, Plot with data with dates. Call signature:: - plot_date( x, y, fmt='bo', tz=None, xdate=True, ydate=False, **kwargs) @@ -4409,7 +4414,7 @@ def xcorr(self, x, y, normed=True, detrend=mlab.detrend_none, return lags, c, a, b def _get_legend_handles(self, legend_handler_map=None): - "return artists that will be used as handles for legend" + """return artists that will be used as handles for legend""" handles_original = self.lines + self.patches + \ self.collections + self.containers @@ -4444,7 +4449,8 @@ def get_legend_handles_labels(self, legend_handler_map=None): labels = [] for handle in self._get_legend_handles(legend_handler_map): label = handle.get_label() - #if (label is not None and label != '' and not label.startswith('_')): + #if (label is not None and label != '' and not + # label.startswith('_')): if label and not label.startswith('_'): handles.append(handle) labels.append(label) @@ -4578,8 +4584,8 @@ def legend(self, *args, **kwargs): if mode is "expand", the legend will be horizontally expanded to fill the axes area (or *bbox_to_anchor*) - *bbox_to_anchor* : an instance of BboxBase or a tuple of 2 or 4 floats - the bbox that the legend will be anchored. + *bbox_to_anchor* : an instance of BboxBase or a tuple of 2 or 4 + floats the bbox that the legend will be anchored. *bbox_transform* : [ an instance of Transform | *None* ] the transform for the bbox. transAxes if *None*. @@ -4593,16 +4599,16 @@ def legend(self, *args, **kwargs): implies a handlelength of 50 points. Values from rcParams will be used if None. - ================ ================================================================== + ================ =================================================== Keyword Description - ================ ================================================================== + ================ =================================================== borderpad the fractional whitespace inside the legend border labelspacing the vertical space between the legend entries handlelength the length of the legend handles handletextpad the pad between the legend handle and text borderaxespad the pad between the axes and legend border columnspacing the spacing between columns - ================ ================================================================== + ================ =================================================== .. Note:: Not all kinds of artist are supported by the legend command. See LINK (FIXME) for details. @@ -4897,8 +4903,8 @@ def make_iterable(x): if orientation == 'vertical': left = [left[i] - width[i] / 2. for i in xrange(len(left))] elif orientation == 'horizontal': - bottom = [bottom[i] - height[i] / - 2. for i in xrange(len(bottom))] + bottom = [bottom[i] - height[i] / 2. + for i in xrange(len(bottom))] else: raise ValueError('invalid alignment: %s' % align) @@ -5040,9 +5046,8 @@ def barh(self, bottom, width, height=0.8, left=None, **kwargs): %(Rectangle)s """ - patches = self.bar( - left=left, height=height, width=width, bottom=bottom, - orientation='horizontal', **kwargs) + patches = self.bar(left=left, height=height, width=width, + bottom=bottom, orientation='horizontal', **kwargs) return patches @docstring.dedent_interpd @@ -5108,8 +5113,10 @@ def stem(self, x, y, linefmt='b-', markerfmt='bo', basefmt='r-', *baseline*). .. seealso:: - This `document `_ - for details. + + This `document + `_ for + details. **Example:** @@ -5176,9 +5183,9 @@ def pie(self, x, explode=None, labels=None, colors=None, A sequence of strings providing the labels for each wedge *autopct*: [ *None* | format string | format function ] - If not *None*, is a string or function used to label the - wedges with their numeric value. The label will be placed inside - the wedge. If it is a format string, the label will be ``fmt%pct``. + If not *None*, is a string or function used to label the wedges + with their numeric value. The label will be placed inside the + wedge. If it is a format string, the label will be ``fmt%pct``. If it is a function, it will be called. *pctdistance*: scalar @@ -5232,6 +5239,8 @@ def pie(self, x, explode=None, labels=None, colors=None, labels = [''] * len(x) if explode is None: explode = [0] * len(x) + + # FIXME don't use assert but raise ValueError assert(len(x) == len(labels)) assert(len(x) == len(explode)) if colors is None: @@ -5701,9 +5710,9 @@ def boxplot(self, x, notch=False, sym='b+', vert=True, whis=1.5, Array or sequence whose first dimension (or length) is compatible with *x* and whose second dimension is 2. When the current element of *conf_intervals* is not None, the notch locations computed by - matplotlib are overridden (assuming notch is True). When an element of - *conf_intervals* is None, boxplot compute notches the method - specified by the other kwargs (e.g. *bootstrap*). + matplotlib are overridden (assuming notch is True). When an + element of *conf_intervals* is None, boxplot compute notches the + method specified by the other kwargs (e.g. *bootstrap*). *positions* : [ default 1,2,...,n ] Sets the horizontal positions of the boxes. The ticks and limits @@ -5805,7 +5814,7 @@ def computeConfInterval(data, med, iq, bootstrap): elif len(usermedians) != col: raise ValueError(msg2) - #sanitize user-input confidence intervals + # sanitize user-input confidence intervals msg1 = "conf_intervals must either be a list of tuples or a 2d array" msg2 = "conf_intervals' length must be compatible with x" msg3 = "each conf_interval, if specificied, must have two values" @@ -5892,7 +5901,8 @@ def computeConfInterval(data, med, iq, bootstrap): # calculate 'notch' plot if notch: # conf. intervals from user, if available - if conf_intervals is not None and conf_intervals[i] is not None: + if (conf_intervals is not None and + conf_intervals[i] is not None): notch_max = np.max(conf_intervals[i]) notch_min = np.min(conf_intervals[i]) else: @@ -5938,12 +5948,14 @@ def patch_list(xs, ys): # vertical or horizontal plot? if vert: + def doplot(*args): return self.plot(*args) def dopatch(xs, ys): return patch_list(xs, ys) else: + def doplot(*args): shuffled = [] for i in xrange(0, len(args), 3): @@ -6121,7 +6133,7 @@ def scatter(self, x, y, s=20, c='b', marker='o', cmap=None, norm=None, edgecolors = 'none' warnings.warn( '''replace "faceted=False" with "edgecolors='none'"''', - DeprecationWarning) # 2008/04/18 + DeprecationWarning) # 2008/04/18 sym = None symstyle = 0 @@ -6402,7 +6414,8 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, if lattice2[i, j] < mincnt: lattice2[i, j] = np.nan accum = np.hstack(( - lattice1.astype(float).ravel(), lattice2.astype(float).ravel())) + lattice1.astype(float).ravel(), + lattice2.astype(float).ravel())) good_idxs = ~np.isnan(accum) else: @@ -6444,8 +6457,9 @@ def hexbin(self, x, y, C=None, gridsize=100, bins=None, else: lattice2[i, j] = np.nan - accum = np.hstack(( - lattice1.astype(float).ravel(), lattice2.astype(float).ravel())) + accum = np.hstack( + (lattice1.astype(float).ravel(), + lattice2.astype(float).ravel())) good_idxs = ~np.isnan(accum) offsets = np.zeros((n, 2), float) @@ -6558,8 +6572,8 @@ def coarse_bin(x, y, coarse): if not valid[i]: continue - verts.append([( - thismin, 0), (thismin, 0.05), (thismax, 0.05), (thismax, 0)]) + verts.append([(thismin, 0), (thismin, 0.05), + (thismax, 0.05), (thismax, 0)]) values.append(val) values = np.array(values) @@ -6587,8 +6601,8 @@ def coarse_bin(x, y, coarse): thismax = thismin + np.diff(coarse)[-1] if not valid[i]: continue - verts.append([(0, thismin), (0.0, thismax), (0.05, - thismax), (0.05, thismin)]) + verts.append([(0, thismin), (0.0, thismax), + (0.05, thismax), (0.05, thismin)]) values.append(val) values = np.array(values) @@ -7339,8 +7353,8 @@ def pcolor(self, *args, **kwargs): X = ma.asarray(X) Y = ma.asarray(Y) mask = ma.getmaskarray(X) + ma.getmaskarray(Y) - xymask = mask[0:-1, 0:-1] + mask[1:, 1:] + mask[0:-1, 1:] + \ - mask[1:, 0:-1] + xymask = (mask[0:-1, 0:-1] + mask[1:, 1:] + mask[0:-1, 1:] + + mask[1:, 0:-1]) # don't plot if C or any of the surrounding vertices are masked. mask = ma.getmaskarray(C)[0:Ny - 1, 0:Nx - 1] + xymask @@ -7476,12 +7490,13 @@ def pcolormesh(self, *args, **kwargs): *vmax* passed in here override any pre-existing values supplied in the *norm* instance. - *shading*: [ 'flat' | 'gouraud' ] + *shading*: ['flat' | 'gouraud'] 'flat' indicates a solid color for each quad. When 'gouraud', each quad will be Gouraud shaded. When gouraud shading, edgecolors is ignored. - *edgecolors*: [ *None* | ``'None'`` | ``'face'`` | color | color sequence] + *edgecolors*: [*None* | ``'None'`` | ``'face'`` | color | + color sequence] If *None*, the rc setting is used by default. If ``'None'``, edges will not be visible. @@ -7524,9 +7539,8 @@ def pcolormesh(self, *args, **kwargs): # convert to one dimensional arrays if shading != 'gouraud': - C = ma.ravel( - C[0:Ny - 1, 0:Nx - 1]) # data point in each cell is value at - # lower left corner + C = ma.ravel(C[0:Ny - 1, 0:Nx - 1]) # data point in each cell is + # value at lower left corner else: C = C.ravel() X = X.ravel() @@ -7702,7 +7716,7 @@ 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 + # at lower left corner X = x.ravel() Y = y.ravel() Nx = nc + 1 @@ -8066,8 +8080,9 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, else: raise ValueError("x must be 1D or 2D") if x.shape[1] < x.shape[0]: - warnings.warn('2D hist input should be nsamples x nvariables;\n ' - 'this looks transposed (shape is %d x %d)' % x.shape[::-1]) + warnings.warn('2D hist input should be nsamples x ' + 'nvariables;\n this looks transposed ' + '(shape is %d x %d)' % x.shape[::-1]) else: # multiple hist with data of different length x = [np.asarray(xi) for xi in x] @@ -8139,8 +8154,9 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, n = [] mlast = bottom - # reversed order is necessary so when stacking histogram, first dataset is on top - # if histogram isn't stacked, this doesn't make any difference + # reversed order is necessary so when stacking histogram, first + # dataset is on top if histogram isn't stacked, this doesn't make any + # difference for i in reversed(xrange(nx)): # this will automatically overwrite bins, # so that each histogram uses the same bins @@ -8272,8 +8288,8 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, elif is_sequence_of_strings(label): labels = list(label) else: - raise ValueError( - 'invalid label: must be string or sequence of strings') + raise ValueError('invalid label: must be string or sequence of ' + 'strings') if len(labels) < nx: labels += [None] * (nx - len(labels)) @@ -8293,11 +8309,11 @@ def hist(self, x, bins=10, range=None, normed=False, weights=None, if binsgiven: if orientation == 'vertical': - self.update_datalim( - [(bins[0], 0), (bins[-1], 0)], updatey=False) + self.update_datalim([(bins[0], 0), (bins[-1], 0)], + updatey=False) else: - self.update_datalim( - [(0, bins[0]), (0, bins[-1])], updatex=False) + self.update_datalim([(0, bins[0]), (0, bins[-1])], + updatex=False) self.set_autoscalex_on(_saved_autoscalex) self.set_autoscaley_on(_saved_autoscaley) @@ -8316,8 +8332,8 @@ def hist2d(self, x, y, bins=10, range=None, normed=False, weights=None, Call signature:: - hist2d(x, y, bins = None, range=None, weights=None, - cmin=None, cmax=None **kwargs) + hist2d(x, y, bins = None, range=None, weights=None, cmin=None, + cmax=None **kwargs) Make a 2d histogram plot of *x* versus *y*, where *x*, *y* are 1-D sequences of the same length. @@ -8910,8 +8926,8 @@ def get_tightbbox(self, renderer, call_axes_locator=True): if bb_yaxis: bb.append(bb_yaxis) - _bbox = mtransforms.Bbox.union( - [b for b in bb if b.width != 0 or b.height != 0]) + _bbox = mtransforms.Bbox.union([b for b in bb + if b.width != 0 or b.height != 0]) return _bbox @@ -8945,7 +8961,6 @@ def triplot(self, *args, **kwargs): mtri.triplot(self, *args, **kwargs) triplot.__doc__ = mtri.triplot.__doc__ - from matplotlib.gridspec import GridSpec, SubplotSpec @@ -9074,7 +9089,6 @@ def _make_twin_axes(self, *kl, **kwargs): ax2 = self.figure.add_subplot(self.get_subplotspec(), *kl, **kwargs) return ax2 - _subplot_classes = {} @@ -9106,6 +9120,7 @@ class _PicklableSubplotClassConstructor(object): class when __call__-ed with an axes class. This is purely to allow Pickling of Axes and Subplots. """ + def __call__(self, axes_class): # create a dummy object instance subplot_instance = _PicklableSubplotClassConstructor()