def get_patches(self): 'return a list of patch instances in the legend' return silent_list('Patch', [h for h in self.handles if isinstance(h, Patch)])
def get_ticklines(self): 'Return the ticklines lines as a list of Line2D instance' lines = [] for tick in self.majorTicks: lines.append(tick.tick1line) lines.append(tick.tick2line) return silent_list('Line2D ticklines', lines)
def get_minorticklines(self): 'Return the minor tick lines as a list of Line2D instances' lines = [] ticks = self.get_minor_ticks() for tick in ticks: lines.append(tick.tick1line) lines.append(tick.tick2line) return silent_list('Line2D ticklines', lines)
def get_ticklabels(self): 'Return a list of Text instances for ticklabels' labels1 = [ tick.label1 for tick in self.get_major_ticks() if tick.label1On ] labels2 = [ tick.label2 for tick in self.get_major_ticks() if tick.label2On ] return silent_list('Text ticklabel', labels1 + labels2)
def __init__(self, ax, *args, **kwargs): """ Draw contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in ContourSet.contour_doc. """ self.ax = ax self.levels = kwargs.get('levels', None) self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) self.colors = kwargs.get('colors', None) norm = kwargs.get('norm', None) self.clip_ends = kwargs.get('clip_ends', None) ######## self.extend = kwargs.get('extend', 'neither') if self.clip_ends is not None: warnings.warn("'clip_ends' has been replaced by 'extend'") self.levels = self.levels[1:-1] # discard specified end levels self.extend = 'both' # regenerate end levels self.antialiased = kwargs.get('antialiased', True) self.nchunk = kwargs.get('nchunk', 0) self.locator = kwargs.get('locator', None) if self.origin is not None: assert (self.origin in ['lower', 'upper', 'image']) if self.extent is not None: assert (len(self.extent) == 4) if cmap is not None: assert (isinstance(cmap, Colormap)) if self.colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if self.origin == 'image': self.origin = rcParams['image.origin'] x, y, z = self._contour_args(*args) # also sets self.levels, # self.layers if self.colors is not None: cmap = ListedColormap(self.colors, N=len(self.layers)) if self.filled: self.collections = silent_list('PolyCollection') else: self.collections = silent_list('LineCollection') # label lists must be initialized here self.cl = [] self.cl_cvalues = [] kw = {'cmap': cmap} if norm is not None: kw['norm'] = norm ScalarMappable.__init__(self, **kw) # sets self.cmap; self._process_colors() if self.filled: if self.linewidths is None: self.linewidths = 0.05 # Good default for Postscript. if iterable(self.linewidths): self.linewidths = self.linewidths[0] #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z)) lowers = self._levels[:-1] uppers = self._levels[1:] for level, level_upper, color in zip(lowers, uppers, self.tcolors): nlist = C.trace(level, level_upper, points=0, nchunk=self.nchunk) col = PolyCollection(nlist, linewidths=(self.linewidths, ), antialiaseds=(self.antialiased, ), facecolors=color, edgecolors='None') self.ax.add_collection(col) self.collections.append(col) else: tlinewidths = self._process_linewidths() self.tlinewidths = tlinewidths #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z)) for level, color, width in zip(self.levels, self.tcolors, tlinewidths): nlist = C.trace(level, points=0) col = LineCollection(nlist, colors=color, linewidths=width) if level < 0.0 and self.monochrome: col.set_linestyle( (0, rcParams['contour.negative_linestyle'])) col.set_label(str(level)) # only for self-documentation self.ax.add_collection(col) self.collections.append(col) x0 = ma.minimum(x) x1 = ma.maximum(x) y0 = ma.minimum(y) y1 = ma.maximum(y) self.ax.update_datalim([(x0, y0), (x1, y1)]) self.ax.set_xlim((x0, x1)) self.ax.set_ylim((y0, y1))
def contourf(self, *args, **kwargs): """ contourf(self, *args, **kwargs) Function signatures contourf(Z) - make a filled contour plot of an array Z. The level values are chosen automatically. contourf(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface contourf(Z,N) and contourf(X,Y,Z,N) - make a filled contour plot corresponding to N contour levels contourf(Z,V) and contourf(X,Y,Z,V) - fill len(V) regions, between the levels specified in sequence V, and a final region for values of Z greater than the last element in V contourf(Z, **kwargs) - Use keyword args to control colors, origin, cmap ... see below [L,C] = contourf(...) returns a list of levels and a silent_list of PolyCollections Optional keywork args are shown with their defaults below (you must use kwargs for these): * colors = None: one of these: - a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all levels will be plotted in this color - if colors == None, the default colormap will be used * alpha=1.0 : the alpha blending value * cmap = None: a cm Colormap instance from matplotlib.cm. * origin = None: 'upper'|'lower'|'image'|None. If 'image', the rc value for image.origin will be used. If None (default), the first value of Z will correspond to the lower left corner, location (0,0). This keyword is active only if contourf is called with one or two arguments, that is, without explicitly specifying X and Y. * badmask = None: array with dimensions of Z, and with values of zero at locations corresponding to valid data, and one at locations where the value of Z should be ignored. This is experimental. It presently works for edge regions for line and filled contours, but for interior regions it works correctly only for line contours. The badmask kwarg may go away in the future, to be replaced by the use of NaN value in Z and/or the use of a masked array in Z. reg is a 1D region number array with of imax*(jmax+1)+1 size The values of reg should be positive region numbers, and zero fro zones wich do not exist. triangle - triangulation array - must be the same shape as reg contourf differs from the Matlab (TM) version in that it does not draw the polygon edges (because the contouring engine yields simply connected regions with branch cuts.) To draw the edges, add line contours with calls to contour. """ alpha = kwargs.get('alpha', 1.0) origin = kwargs.get('origin', None) extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) colors = kwargs.get('colors', None) badmask = kwargs.get('badmask', None) if cmap is not None: assert(isinstance(cmap, Colormap)) if origin is not None: assert(origin in ['lower', 'upper', 'image']) if colors is not None and cmap is not None: raise RuntimeError('Either colors or cmap must be None') if origin == 'image': origin = rcParams['image.origin'] x, y, z, lev = self._contour_args(True, badmask, origin, extent, *args) # Manipulate the plot *after* checking the input arguments. if not self.ax.ishold(): self.ax.cla() Nlev = len(lev) reg, triangle = self._initialize_reg_tri(z, badmask) tcolors, mappable, collections = self._process_colors(z, colors, alpha, lev, cmap) region = 0 lev_upper = list(lev[1:]) lev_upper.append(1e38) for level, level_upper, color in zip(lev, lev_upper, tcolors): levs = (level, level_upper) ntotal, nparts = _contour.GcInit2(x, y, reg, triangle, region, z, levs, 30) np = zeros((nparts,), typecode='l') xp = zeros((ntotal, ), Float64) yp = zeros((ntotal,), Float64) nlist = _contour.GcTrace(np, xp, yp) col = PolyCollection(nlist, linewidths=(1,)) # linewidths = 1 is necessary to avoid artifacts # in rendering the region boundaries. col.set_color(color) # sets both facecolor and edgecolor self.ax.add_collection(col) collections.append(col) collections = silent_list('PolyCollection', collections) collections.mappable = mappable return lev, collections
def get_gridlines(self): 'Return the grid lines as a list of Line2D instance' return silent_list('Line2D gridline', [tick.gridline for tick in self.majorTicks])
def get_ticklabels(self): 'Return a list of Text instances for ticklabels' labels1 = [tick.label1 for tick in self.get_major_ticks() if tick.label1On] labels2 = [tick.label2 for tick in self.get_major_ticks() if tick.label2On] return silent_list('Text ticklabel', labels1+labels2)
def clabel(self, *args, **kwargs): """ clabel(CS, **kwargs) - add labels to line contours in CS, where CS is a ContourSet object returned by contour. clabel(CS, V, **kwargs) - only label contours listed in V keyword arguments: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = True: controls whether the underlying contour is removed (inline = True) or not (False) * fmt = '%1.3f': a format string for the label """ fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 1) self.fmt = kwargs.get('fmt', '%1.3f') colors = kwargs.get('colors', None) if len(args) == 0: levels = self.levels indices = range(len(self.levels)) elif len(args) == 1: levlabs = list(args[0]) indices, levels = [], [] for i, lev in enumerate(self.levels): if lev in levlabs: indices.append(i) levels.append(lev) if len(levels) < len(levlabs): msg = "Specified levels " + str(levlabs) msg += "\n don't match available levels " msg += str(self.levels) raise ValueError(msg) else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.label_levels = levels self.label_indices = indices self.fp = FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") # Can't it be floating point, as indicated in line above? else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize self.fslist = [font_size] * len(levels) if colors == None: self.label_mappable = self self.label_cvalues = take(self.cvalues, self.label_indices) else: cmap = ListedColormap(colors, N=len(self.label_levels)) self.label_cvalues = range(len(self.label_levels)) self.label_mappable = ScalarMappable(cmap = cmap, norm = no_norm()) #self.cl = [] # Initialized in ContourSet.__init__ #self.cl_cvalues = [] # same self.cl_xy = [] self.labels(inline) for label in self.cl: self.ax.add_artist(label) self.label_list = silent_list('Text', self.cl) return self.label_list
def __init__(self, ax, *args, **kwargs): """ Draw contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in ContourSet.contour_doc. """ self.ax = ax self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) self.colors = kwargs.get('colors', None) norm = kwargs.get('norm', None) self.clip_ends = kwargs.get('clip_ends', True) self.antialiased = kwargs.get('antialiased', True) self.nchunk = kwargs.get('nchunk', 0) if self.origin is not None: assert(self.origin in ['lower', 'upper', 'image']) if self.extent is not None: assert(len(self.extent) == 4) if cmap is not None: assert(isinstance(cmap, Colormap)) if self.colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if self.origin == 'image': self.origin = rcParams['image.origin'] x, y, z = self._contour_args(*args) # also sets self.levels, # self.layers if self.colors is not None: cmap = ListedColormap(self.colors, N=len(self.layers)) if self.filled: self.collections = silent_list('PolyCollection') else: self.collections = silent_list('LineCollection') # label lists must be initialized here self.cl = [] self.cl_cvalues = [] kw = {'cmap': cmap} if norm is not None: kw['norm'] = norm ScalarMappable.__init__(self, **kw) # sets self.cmap; self._process_colors() if self.filled: if self.linewidths is None: self.linewidths = 0.05 # Good default for Postscript. if iterable(self.linewidths): self.linewidths = self.linewidths[0] #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z)) lowers = self.levels[:-1] uppers = self.levels[1:] for level, level_upper, color in zip(lowers, uppers, self.tcolors): nlist = C.trace(level, level_upper, points = 1, nchunk = self.nchunk) col = PolyCollection(nlist, linewidths = (self.linewidths,), antialiaseds = (self.antialiased,)) col.set_color(color) # sets both facecolor and edgecolor self.ax.add_collection(col) self.collections.append(col) else: tlinewidths = self._process_linewidths() #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z)) for level, color, width in zip(self.levels, self.tcolors, tlinewidths): nlist = C.trace(level, points = 1) col = LineCollection(nlist) col.set_color(color) col.set_linewidth(width) if level < 0.0 and self.monochrome: col.set_linestyle((0, (6.,6.)),) col.set_label(str(level)) # only for self-documentation self.ax.add_collection(col) self.collections.append(col) ## check: seems like set_xlim should also be inside if not self.ax.ishold(): self.ax.cla() self.ax.set_xlim((ma.minimum(x), ma.maximum(x))) self.ax.set_ylim((ma.minimum(y), ma.maximum(y)))
def contourf(self, *args, **kwargs): """ contourf(self, *args, **kwargs) Function signatures contourf(Z) - make a filled contour plot of an array Z. The level values are chosen automatically. contourf(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface contourf(Z,N) and contourf(X,Y,Z,N) - make a filled contour plot corresponding to N contour levels contourf(Z,V) and contourf(X,Y,Z,V) - fill len(V) regions, between the levels specified in sequence V, and a final region for values of Z greater than the last element in V contourf(Z, **kwargs) - Use keyword args to control colors, origin, cmap ... see below [L,C] = contourf(...) returns a list of levels and a silent_list of PolyCollections Optional keywork args are shown with their defaults below (you must use kwargs for these): * colors = None: one of these: - a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all levels will be plotted in this color - if colors == None, the default colormap will be used * alpha=1.0 : the alpha blending value * cmap = None: a cm Colormap instance from matplotlib.cm. * origin = None: 'upper'|'lower'|'image'|None. If 'image', the rc value for image.origin will be used. If None (default), the first value of Z will correspond to the lower left corner, location (0,0). This keyword is active only if contourf is called with one or two arguments, that is, without explicitly specifying X and Y. * badmask = None: array with dimensions of Z, and with values of zero at locations corresponding to valid data, and one at locations where the value of Z should be ignored. This is experimental. It presently works for edge regions for line and filled contours, but for interior regions it works correctly only for line contours. The badmask kwarg may go away in the future, to be replaced by the use of NaN value in Z and/or the use of a masked array in Z. reg is a 1D region number array with of imax*(jmax+1)+1 size The values of reg should be positive region numbers, and zero fro zones wich do not exist. triangle - triangulation array - must be the same shape as reg contourf differs from the Matlab (TM) version in that it does not draw the polygon edges (because the contouring engine yields simply connected regions with branch cuts.) To draw the edges, add line contours with calls to contour. """ alpha = kwargs.get('alpha', 1.0) origin = kwargs.get('origin', None) extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) colors = kwargs.get('colors', None) badmask = kwargs.get('badmask', None) if cmap is not None: assert (isinstance(cmap, Colormap)) if origin is not None: assert (origin in ['lower', 'upper', 'image']) if colors is not None and cmap is not None: raise RuntimeError('Either colors or cmap must be None') if origin == 'image': origin = rcParams['image.origin'] x, y, z, lev = self._contour_args(True, badmask, origin, extent, *args) # Manipulate the plot *after* checking the input arguments. if not self.ax.ishold(): self.ax.cla() Nlev = len(lev) reg, triangle = self._initialize_reg_tri(z, badmask) tcolors, mappable, collections = self._process_colors( z, colors, alpha, lev, cmap) region = 0 lev_upper = list(lev[1:]) lev_upper.append(1e38) for level, level_upper, color in zip(lev, lev_upper, tcolors): levs = (level, level_upper) ntotal, nparts = _contour.GcInit2(x, y, reg, triangle, region, z, levs, 30) np = zeros((nparts, ), typecode='l') xp = zeros((ntotal, ), Float64) yp = zeros((ntotal, ), Float64) nlist = _contour.GcTrace(np, xp, yp) col = PolyCollection(nlist, linewidths=(1, )) # linewidths = 1 is necessary to avoid artifacts # in rendering the region boundaries. col.set_color(color) # sets both facecolor and edgecolor self.ax.add_collection(col) collections.append(col) collections = silent_list('PolyCollection', collections) collections.mappable = mappable return lev, collections
def get_minorticklabels(self): 'Return a list of Text instances for the minor ticklabels' ticks = self.get_minor_ticks() labels1 = [tick.label1 for tick in ticks if tick.label1On] labels2 = [tick.label2 for tick in ticks if tick.label2On] return silent_list('Text minor ticklabel', labels1+labels2)
def __init__(self, ax, *args, **kwargs): """ Draw contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in ContourSet.contour_doc. """ self.ax = ax self.levels = kwargs.get('levels', None) self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) self.colors = kwargs.get('colors', None) norm = kwargs.get('norm', None) self.clip_ends = kwargs.get('clip_ends', None) ######## self.extend = kwargs.get('extend', 'neither') if self.clip_ends is not None: warnings.warn("'clip_ends' has been replaced by 'extend'") self.levels = self.levels[1:-1] # discard specified end levels self.extend = 'both' # regenerate end levels self.antialiased = kwargs.get('antialiased', True) self.nchunk = kwargs.get('nchunk', 0) self.locator = kwargs.get('locator', None) if self.origin is not None: assert(self.origin in ['lower', 'upper', 'image']) if self.extent is not None: assert(len(self.extent) == 4) if cmap is not None: assert(isinstance(cmap, Colormap)) if self.colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if self.origin == 'image': self.origin = rcParams['image.origin'] x, y, z = self._contour_args(*args) # also sets self.levels, # self.layers if self.colors is not None: cmap = ListedColormap(self.colors, N=len(self.layers)) if self.filled: self.collections = silent_list('PolyCollection') else: self.collections = silent_list('LineCollection') # label lists must be initialized here self.cl = [] self.cl_cvalues = [] kw = {'cmap': cmap} if norm is not None: kw['norm'] = norm ScalarMappable.__init__(self, **kw) # sets self.cmap; self._process_colors() if self.filled: if self.linewidths is None: self.linewidths = 0.05 # Good default for Postscript. if iterable(self.linewidths): self.linewidths = self.linewidths[0] #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z)) lowers = self._levels[:-1] uppers = self._levels[1:] for level, level_upper, color in zip(lowers, uppers, self.tcolors): nlist = C.trace(level, level_upper, points = 0, nchunk = self.nchunk) col = PolyCollection(nlist, linewidths = (self.linewidths,), antialiaseds = (self.antialiased,), facecolors= color, edgecolors= 'None') self.ax.add_collection(col) self.collections.append(col) else: tlinewidths = self._process_linewidths() self.tlinewidths = tlinewidths #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmaskorNone(z)) for level, color, width in zip(self.levels, self.tcolors, tlinewidths): nlist = C.trace(level, points = 0) col = LineCollection(nlist, colors = color, linewidths = width) if level < 0.0 and self.monochrome: col.set_linestyle((0, rcParams['contour.negative_linestyle'])) col.set_label(str(level)) # only for self-documentation self.ax.add_collection(col) self.collections.append(col) x0 = ma.minimum(x) x1 = ma.maximum(x) y0 = ma.minimum(y) y1 = ma.maximum(y) self.ax.update_datalim([(x0,y0), (x1,y1)]) self.ax.set_xlim((x0, x1)) self.ax.set_ylim((y0, y1))
def get_texts(self): 'return a list of text.Text instance in the legend' return silent_list('Text', self.texts)
def clabel(self, *args, **kwargs): """ clabel(CS, **kwargs) - add labels to line contours in CS, where CS is a ContourSet object returned by contour. clabel(CS, V, **kwargs) - only label contours listed in V keyword arguments: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = True: controls whether the underlying contour is removed (inline = True) or not (False) * fmt = '%1.3f': a format string for the label """ fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 1) self.fmt = kwargs.get('fmt', '%1.3f') colors = kwargs.get('colors', None) if len(args) == 0: levels = self.levels indices = range(len(self.levels)) elif len(args) == 1: levlabs = list(args[0]) indices, levels = [], [] for i, lev in enumerate(self.levels): if lev in levlabs: indices.append(i) levels.append(lev) if len(levels) < len(levlabs): msg = "Specified levels " + str(levlabs) msg += "\n don't match available levels " msg += str(self.levels) raise ValueError(msg) else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.label_levels = levels self.label_indices = indices self.fp = FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") # Can't it be floating point, as indicated in line above? else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize self.fslist = [font_size] * len(levels) if colors == None: self.label_mappable = self self.label_cvalues = take(self.cvalues, self.label_indices) else: cmap = ListedColormap(colors, N=len(self.label_levels)) self.label_cvalues = range(len(self.label_levels)) self.label_mappable = ScalarMappable(cmap=cmap, norm=no_norm()) #self.cl = [] # Initialized in ContourSet.__init__ #self.cl_cvalues = [] # same self.cl_xy = [] self.labels(inline) for label in self.cl: self.ax.add_artist(label) self.label_list = silent_list('Text', self.cl) return self.label_list
def clabel(self, *args, **kwargs): """ CLABEL(*args, **kwargs) Function signatures CLABEL(C) - plots contour labels, C is the output of contour or a list of contours CLABEL(C,V) - creates labels only for those contours, given in a list V CLABEL(C, **kwargs) - keyword args are explained below: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = 0: controls whether the underlying contour is removed (inline = 1) or not * fmt = '%1.3f': a format string for the label """ # todo, factor this out to a separate class and don't use hidden coll attrs if not self.ax.ishold(): self.ax.cla() fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 0) fmt = kwargs.get('fmt', '%1.3f') colors = kwargs.get('colors', None) if len(args) == 1: contours = args[0] levels = [con._label for con in contours] elif len(args) == 2: contours = args[0] levels = args[1] else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.fp = FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize fslist = [font_size] * len(levels) if colors == None: colors = [c._colors[0] for c in contours] else: colors = colors * len(contours) if inline not in [0,1]: raise TypeError("inline must be 0 or 1") self.cl = [] self.cl_xy = [] # we have a list of contours and each contour has a list of # segments. We want changes in the contour color to be # reflected in changes in the label color. This is a good use # for traits observers, but in the interim, until traits are # utilized, we'll create a dict mapping i,j to text instances. # i is the contour level index, j is the sement index self.labeld = {} if inline == 1: self.inline_labels(levels, contours, colors, fslist, fmt) else: self.labels(levels, contours, colors, fslist, fmt) for label in self.cl: self.ax.add_artist(label) ret = silent_list('Text', self.cl) ret.mappable = getattr(contours, 'mappable', None) # support colormapping for label if ret.mappable is not None: ret.mappable.labeld = self.labeld return ret
def contourf(self, *args, **kwargs): """ contourf(self, *args, **kwargs) Function signatures contourf(Z) - make a filled contour plot of an array Z. The level values are chosen automatically. contourf(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface contourf(Z,N) and contourf(X,Y,Z,N) - make a filled contour plot corresponding to N contour levels contourf(Z,V) and contourf(X,Y,Z,V) - fill len(V)-1 regions, between the levels specified in sequence V contourf(Z, **kwargs) - Use keyword args to control colors, origin, cmap ... see below [L,C] = contourf(...) returns a list of levels and a silent_list of PolyCollections Z may be a masked array, but a bug remains to be fixed. Optional keyword args are shown with their defaults below (you must use kwargs for these): * colors = None, or one of the following: - a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all levels will be plotted in this color - if colors == None, the default colormap will be used * alpha=1.0 : the alpha blending value * cmap = None: a cm Colormap instance from matplotlib.cm. * origin = None: 'upper'|'lower'|'image'|None. If 'image', the rc value for image.origin will be used. If None (default), the first value of Z will correspond to the lower left corner, location (0,0). This keyword is active only if contourf is called with one or two arguments, that is, without explicitly specifying X and Y. * extent = None: (x0,x1,y0,y1); also active only if X and Y are not specified. contourf differs from the Matlab (TM) version in that it does not draw the polygon edges (because the contouring engine yields simply connected regions with branch cuts.) To draw the edges, add line contours with calls to contour. """ alpha = kwargs.get('alpha', 1.0) origin = kwargs.get('origin', None) extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) colors = kwargs.get('colors', None) if cmap is not None: assert(isinstance(cmap, Colormap)) if origin is not None: assert(origin in ['lower', 'upper', 'image']) if colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if origin == 'image': origin = rcParams['image.origin'] x, y, z, lev = self._contour_args(True, origin, extent, *args) # Manipulate the plot *after* checking the input arguments. if not self.ax.ishold(): self.ax.cla() tcolors, mappable, collections = self._process_colors(colors, alpha, lev[:-1], cmap) C = _contour.Cntr(x, y, z.filled(), z.mask()) for level, level_upper, color in zip(lev[:-1], lev[1:], tcolors): nlist = C.trace(level, level_upper, points = 1) col = PolyCollection(nlist, linewidths=(1,)) # linewidths = 1 is necessary to avoid artifacts # in rendering the region boundaries. col.set_color(color) # sets both facecolor and edgecolor self.ax.add_collection(col) collections.append(col) collections = silent_list('PolyCollection', collections) collections.mappable = mappable return lev, collections
def contour(self, *args, **kwargs): """ contour(self, *args, **kwargs) Function signatures contour(Z) - make a contour plot of an array Z. The level values are chosen automatically. contour(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface contour(Z,N) and contour(X,Y,Z,N) - draw N contour lines overriding the automatic value contour(Z,V) and contour(X,Y,Z,V) - draw len(V) contour lines, at the values specified in V (array, list, tuple) contour(Z, **kwargs) - Use keyword args to control colors, linewidth, origin, cmap ... see below [L,C] = contour(...) returns a list of levels and a silent_list of LineCollections Z may be a masked array. Optional keywork args are shown with their defaults below (you must use kwargs for these): * colors = None; or one of the following: - a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all levels will be plotted in this color - if colors == None, the default colormap will be used * alpha=1.0 : the alpha blending value * cmap = None: a cm Colormap instance from matplotlib.cm. * origin = None: 'upper'|'lower'|'image'|None. If 'image', the rc value for image.origin will be used. If None (default), the first value of Z will correspond to the lower left corner, location (0,0). This keyword is active only if contourf is called with one or two arguments, that is, without explicitly specifying X and Y. * extent = None: (x0,x1,y0,y1); also active only if X and Y are not specified. * linewidths = None: or one of these: - a number - all levels will be plotted with this linewidth, e.g. linewidths = 0.6 - a tuple of numbers, e.g. linewidths = (0.4, 0.8, 1.2) different levels will be plotted with different linewidths in the order specified - if linewidths == None, the default width in lines.linewidth in .matplotlibrc is used * fmt = '1.3f': a format string for adding a label to each collection. Useful for auto-legending. """ alpha = kwargs.get('alpha', 1.0) linewidths = kwargs.get('linewidths', None) fmt = kwargs.get('fmt', '%1.3f') origin = kwargs.get('origin', None) extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) colors = kwargs.get('colors', None) if cmap is not None: assert(isinstance(cmap, Colormap)) if origin is not None: assert(origin in ['lower', 'upper', 'image']) if extent is not None: assert(len(extent) == 4) if colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if origin == 'image': origin = rcParams['image.origin'] x, y, z, lev = self._contour_args(False, origin, extent, *args) # Manipulate the plot *after* checking the input arguments. if not self.ax.ishold(): self.ax.cla() Nlev = len(lev) if cmap is None: if colors is None: Ncolors = Nlev else: Ncolors = len(colors) else: Ncolors = Nlev tcolors, mappable, collections = self._process_colors(colors, alpha, lev, cmap) if linewidths == None: tlinewidths = [rcParams['lines.linewidth']] *Nlev else: if iterable(linewidths) and len(linewidths) < Nlev: linewidths = list(linewidths) * int(ceil(Nlev/len(linewidths))) elif not iterable(linewidths) and type(linewidths) in [int, float]: linewidths = [linewidths] * Nlev tlinewidths = [(w,) for w in linewidths] C = _contour.Cntr(x, y, z.filled(), z.mask()) for level, color, width in zip(lev, tcolors, tlinewidths): nlist = C.trace(level, points = 1) col = LineCollection(nlist) col.set_color(color) col.set_linewidth(width) if level < 0.0 and Ncolors == 1: col.set_linestyle((0, (6.,6.)),) #print "setting dashed" col.set_label(fmt%level) self.ax.add_collection(col) collections.append(col) collections = silent_list('LineCollection', collections) # the mappable attr is for the pylab interface functions, # which maintain the current image collections.mappable = mappable return lev, collections
def __init__(self, ax, *args, **kwargs): """ Draw contour lines or filled regions, depending on whether keyword arg 'filled' is False (default) or True. The first argument of the initializer must be an axes object. The remaining arguments and keyword arguments are described in ContourSet.contour_doc. """ self.ax = ax self.filled = kwargs.get('filled', False) self.linewidths = kwargs.get('linewidths', None) self.alpha = kwargs.get('alpha', 1.0) self.origin = kwargs.get('origin', None) self.extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) self.colors = kwargs.get('colors', None) self.clip_ends = kwargs.get('clip_ends', True) self.antialiased = kwargs.get('antialiased', True) self.nchunk = kwargs.get('nchunk', 0) if self.origin is not None: assert(self.origin in ['lower', 'upper', 'image']) if self.extent is not None: assert(len(self.extent) == 4) if cmap is not None: assert(isinstance(cmap, Colormap)) if self.colors is not None and cmap is not None: raise ValueError('Either colors or cmap must be None') if self.origin == 'image': self.origin = rcParams['image.origin'] x, y, z = self._contour_args(*args) # also sets self.levels, # self.layers if self.colors is not None: cmap = ListedColormap(self.colors, N=len(self.layers)) if self.filled: self.collections = silent_list('PolyCollection') else: self.collections = silent_list('LineCollection') # label lists must be initialized here self.cl = [] self.cl_cvalues = [] ScalarMappable.__init__(self, cmap = cmap) # sets self.cmap; # default norm for now self._process_colors() if self.filled: if self.linewidths is None: self.linewidths = 0.05 # Good default for Postscript. if iterable(self.linewidths): self.linewidths = self.linewidths[0] #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmask(z)) lowers = self.levels[:-1] uppers = self.levels[1:] for level, level_upper, color in zip(lowers, uppers, self.tcolors): nlist = C.trace(level, level_upper, points = 1, nchunk = self.nchunk) col = PolyCollection(nlist, linewidths = (self.linewidths,), antialiaseds = (self.antialiased,)) col.set_color(color) # sets both facecolor and edgecolor self.ax.add_collection(col) self.collections.append(col) else: tlinewidths = self._process_linewidths() #C = _contour.Cntr(x, y, z.filled(), z.mask()) C = _contour.Cntr(x, y, z.filled(), ma.getmask(z)) for level, color, width in zip(self.levels, self.tcolors, tlinewidths): nlist = C.trace(level, points = 1) col = LineCollection(nlist) col.set_color(color) col.set_linewidth(width) if level < 0.0 and self.monochrome: col.set_linestyle((0, (6.,6.)),) #print "setting dashed" col.set_label(str(level)) # only for self-documentation self.ax.add_collection(col) self.collections.append(col) ## check: seems like set_xlim should also be inside if not self.ax.ishold(): self.ax.cla() self.ax.set_xlim((ma.minimum(x), ma.maximum(x))) self.ax.set_ylim((ma.minimum(y), ma.maximum(y)))
def get_gridlines(self): "Return the grid lines as a list of Line2D instance" return silent_list("Line2D gridline", [tick.gridline for tick in self.majorTicks])
def get_patches(self): "return a list of patch instances in the legend" return silent_list("Patch", [h for h in self.legendHandles if isinstance(h, Patch)])
def contour(self, *args, **kwargs): """ contour(self, *args, **kwargs) Function signatures contour(Z) - make a contour plot of an array Z. The level values are chosen automatically. contour(X,Y,Z) - X,Y specify the (x,y) coordinates of the surface contour(Z,N) and contour(X,Y,Z,N) - draw N contour lines overriding the automatic value contour(Z,V) and contour(X,Y,Z,V) - draw len(V) contour lines, at the values specified in V (array, list, tuple) contour(Z, **kwargs) - Use keyword args to control colors, linewidth, origin, cmap ... see below [L,C] = contour(...) returns a list of levels and a silent_list of LineCollections Optional keywork args are shown with their defaults below (you must use kwargs for these): * colors = None: one of these: - a tuple of matplotlib color args (string, float, rgb, etc), different levels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all levels will be plotted in this color - if colors == None, the default colormap will be used * alpha=1.0 : the alpha blending value * cmap = None: a cm Colormap instance from matplotlib.cm. * origin = None: 'upper'|'lower'|'image'|None. If 'image', the rc value for image.origin will be used. If None (default), the first value of Z will correspond to the lower left corner, location (0,0). This keyword is active only if contourf is called with one or two arguments, that is, without explicitly specifying X and Y. * extent = None: (x0,x1,y0,y1); also active only if X and Y are not specified. * badmask = None: array with dimensions of Z, and with values of zero at locations corresponding to valid data, and one at locations where the value of Z should be ignored. This is experimental. It presently works for edge regions for line and filled contours, but for interior regions it works correctly only for line contours. The badmask kwarg may go away in the future, to be replaced by the use of NaN value in Z and/or the use of a masked array in Z. * linewidths = None: or one of these: - a number - all levels will be plotted with this linewidth, e.g. linewidths = 0.6 - a tuple of numbers, e.g. linewidths = (0.4, 0.8, 1.2) different levels will be plotted with different linewidths in the order specified - if linewidths == None, the default width in lines.linewidth in .matplotlibrc is used * fmt = '1.3f': a format string for adding a label to each collection. Useful for auto-legending. """ alpha = kwargs.get('alpha', 1.0) linewidths = kwargs.get('linewidths', None) fmt = kwargs.get('fmt', '%1.3f') origin = kwargs.get('origin', None) extent = kwargs.get('extent', None) cmap = kwargs.get('cmap', None) colors = kwargs.get('colors', None) badmask = kwargs.get('badmask', None) if cmap is not None: assert (isinstance(cmap, Colormap)) if origin is not None: assert (origin in ['lower', 'upper', 'image']) if extent is not None: assert (len(extent) == 4) if colors is not None and cmap is not None: raise RuntimeError('Either colors or cmap must be None') # todo: shouldn't this use the current image rather than the rc param? if origin == 'image': origin = rcParams['image.origin'] x, y, z, lev = self._contour_args(False, badmask, origin, extent, *args) # Manipulate the plot *after* checking the input arguments. if not self.ax.ishold(): self.ax.cla() Nlev = len(lev) if cmap is None: if colors is None: Ncolors = Nlev else: Ncolors = len(colors) else: Ncolors = Nlev reg, triangle = self._initialize_reg_tri(z, badmask) tcolors, mappable, collections = self._process_colors( z, colors, alpha, lev, cmap) if linewidths == None: tlinewidths = [rcParams['lines.linewidth']] * Nlev else: if iterable(linewidths) and len(linewidths) < Nlev: linewidths = list(linewidths) * int( ceil(Nlev / len(linewidths))) elif not iterable(linewidths) and type(linewidths) in [int, float]: linewidths = [linewidths] * Nlev tlinewidths = [(w, ) for w in linewidths] region = 0 for level, color, width in zip(lev, tcolors, tlinewidths): ntotal, nparts = _contour.GcInit1(x, y, reg, triangle, region, z, level) np = zeros((nparts, ), typecode='l') xp = zeros((ntotal, ), Float64) yp = zeros((ntotal, ), Float64) nlist = _contour.GcTrace(np, xp, yp) col = LineCollection(nlist) col.set_color(color) col.set_linewidth(width) if level < 0.0 and Ncolors == 1: col.set_linestyle((0, (6., 6.)), ) #print "setting dashed" col.set_label(fmt % level) self.ax.add_collection(col) collections.append(col) collections = silent_list('LineCollection', collections) # the mappable attr is for the pylab interface functions, # which maintain the current image collections.mappable = mappable return lev, collections
def get_texts(self): "return a list of text.Text instance in the legend" return silent_list("Text", self.texts)
def clabel(self, *args, **kwargs): """ CLABEL(*args, **kwargs) Function signatures CLABEL(C) - plots contour labels, C is the output of contour or a list of contours CLABEL(C,V) - creates labels only for those contours, given in a list V CLABEL(C, **kwargs) - keyword args are explained below: * fontsize = None: as described in http://matplotlib.sf.net/fonts.html * colors = None: - a tuple of matplotlib color args (string, float, rgb, etc), different labels will be plotted in different colors in the order specified - one string color, e.g. colors = 'r' or colors = 'red', all labels will be plotted in this color - if colors == None, the color of each label matches the color of the corresponding contour * inline = 0: controls whether the underlying contour is removed (inline = 1) or not * fmt = '%1.3f': a format string for the label """ # todo, factor this out to a separate class and don't use hidden coll attrs if not self.ax.ishold(): self.ax.cla() fontsize = kwargs.get('fontsize', None) inline = kwargs.get('inline', 0) fmt = kwargs.get('fmt', '%1.3f') colors = kwargs.get('colors', None) if len(args) == 1: contours = args[0] levels = [con._label for con in contours] elif len(args) == 2: contours = args[0] levels = args[1] else: raise TypeError("Illegal arguments to clabel, see help(clabel)") self.fp = FontProperties() if fontsize == None: font_size = int(self.fp.get_size_in_points()) else: if type(fontsize) not in [int, float, str]: raise TypeError("Font size must be an integer number.") else: if type(fontsize) == str: font_size = int(self.fp.get_size_in_points()) else: self.fp.set_size(fontsize) font_size = fontsize fslist = [font_size] * len(levels) if colors == None: colors = [c._colors[0] for c in contours] else: colors = colors * len(contours) if inline not in [0, 1]: raise TypeError("inline must be 0 or 1") self.cl = [] self.cl_xy = [] # we have a list of contours and each contour has a list of # segments. We want changes in the contour color to be # reflected in changes in the label color. This is a good use # for traits observers, but in the interim, until traits are # utilized, we'll create a dict mapping i,j to text instances. # i is the contour level index, j is the sement index self.labeld = {} if inline == 1: self.inline_labels(levels, contours, colors, fslist, fmt) else: self.labels(levels, contours, colors, fslist, fmt) for label in self.cl: self.ax.add_artist(label) ret = silent_list('Text', self.cl) ret.mappable = getattr(contours, 'mappable', None) # support colormapping for label if ret.mappable is not None: ret.mappable.labeld = self.labeld return ret
def get_gridlines(self): 'Return the grid lines as a list of Line2D instance' ticks = self.get_major_ticks() return silent_list('Line2D gridline', [tick.gridline for tick in ticks])