def _autolev(self, z, N): ''' Select contour levels to span the data. We need two more levels for filled contours than for line contours, because for the latter we need to specify the lower and upper boundary of each range. For example, a single contour boundary, say at z = 0, requires only one contour line, but two filled regions, and therefore three levels to provide boundaries for both regions. ''' zmax = ma.maximum(z) zmin = ma.minimum(z) zmargin = (zmax - zmin) * 0.001 # so z < (zmax + zmargin) if self.filled: lev = linspace(zmin, zmax + zmargin, N+2) else: lev = linspace(zmin, zmax + zmargin, N+2)[1:-1] return lev
def _autolev(self, z, N, filled): ''' Select contour levels to span the data. We need two more levels for filled contours than for line contours, because for the latter we need to specify the lower and upper boundary of each range. For example, a single contour boundary, say at z = 0, requires only one contour line, but two filled regions, and therefore three levels to provide boundaries for both regions. ''' zmax = ma.maximum(z) zmin = ma.minimum(z) zmargin = (zmax - zmin) * 0.001 # so z < (zmax + zmargin) if filled: lev = linspace(zmin, zmax + zmargin, N+2) else: lev = linspace(zmin, zmax + zmargin, N+2)[1:-1] return lev
def _autolev(self, z, N, filled, badmask): ''' Select contour levels to span the data. We need one more level for filled contours than for line contours, because for the latter we need to specify the lower and upper boundary of each range. For example, a single contour boundary, say at z = 0, requires only one contour line, but two filled regions, and therefore two levels. These are taken as the lower boundaries of the regions. ''' rz = ma.masked_array(z, badmask) zmax = ma.maximum(rz) # was: zmax = amax(rz) zmin = ma.minimum(rz) if filled: lev = linspace(zmin, zmax, N + 2)[:-1] else: lev = linspace(zmin, zmax, N + 2)[1:-1] return lev
def _autolev(self, z, N, filled, badmask): ''' Select contour levels to span the data. We need one more level for filled contours than for line contours, because for the latter we need to specify the lower and upper boundary of each range. For example, a single contour boundary, say at z = 0, requires only one contour line, but two filled regions, and therefore two levels. These are taken as the lower boundaries of the regions. ''' rz = ma.masked_array(z, badmask) zmax = ma.maximum(rz) # was: zmax = amax(rz) zmin = ma.minimum(rz) if filled: lev = linspace(zmin, zmax, N+2)[:-1] else: lev = linspace(zmin, zmax, N+2)[1:-1] return lev
def __init__(self, ax, labels, active=0, activecolor='blue'): """ Add radio buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings active is the index into labels for the button that is active activecolor is the color of the button when clicked """ self.activecolor = activecolor ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) dy = 1. / (len(labels) + 1) ys = linspace(1 - dy, dy, len(labels)) cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.circles = [] for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') if cnt == active: facecolor = activecolor else: facecolor = axcolor p = Circle(xy=(0.15, y), radius=0.05, facecolor=facecolor, transform=ax.transAxes) self.labels.append(t) self.circles.append(p) ax.add_patch(p) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
def _initialize_x_y(self, z): ''' Return X, Y arrays such that contour(Z) will match imshow(Z) if origin is not None. The center of pixel Z[i,j] depends on origin: if origin is None, x = j, y = i; if origin is 'lower', x = j + 0.5, y = i + 0.5; if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5 If extent is not None, x and y will be scaled to match, as in imshow. If origin is None and extent is not None, then extent will give the minimum and maximum values of x and y. ''' if len(shape(z)) != 2: raise TypeError("Input must be a 2D array.") else: Ny, Nx = shape(z) if self.origin is None: # Not for image-matching. if self.extent is None: return meshgrid(arange(Nx), arange(Ny)) else: x0,x1,y0,y1 = self.extent x = linspace(x0, x1, Nx) y = linspace(y0, y1, Ny) return meshgrid(x, y) # Match image behavior: if self.extent is None: x0,x1,y0,y1 = (0, Nx, 0, Ny) else: x0,x1,y0,y1 = self.extent dx = float(x1 - x0)/Nx dy = float(y1 - y0)/Ny x = x0 + (arange(Nx) + 0.5) * dx y = y0 + (arange(Ny) + 0.5) * dy if self.origin == 'upper': y = y[::-1] return meshgrid(x,y)
def _initialize_x_y(self, z): ''' Return X, Y arrays such that contour(Z) will match imshow(Z) if origin is not None. The center of pixel Z[i,j] depends on origin: if origin is None, x = j, y = i; if origin is 'lower', x = j + 0.5, y = i + 0.5; if origin is 'upper', x = j + 0.5, y = Nrows - i - 0.5 If extent is not None, x and y will be scaled to match, as in imshow. If origin is None and extent is not None, then extent will give the minimum and maximum values of x and y. ''' if len(shape(z)) != 2: raise TypeError("Input must be a 2D array.") else: Ny, Nx = shape(z) if self.origin is None: # Not for image-matching. if self.extent is None: return meshgrid(arange(Nx), arange(Ny)) else: x0, x1, y0, y1 = self.extent x = linspace(x0, x1, Nx) y = linspace(y0, y1, Ny) return meshgrid(x, y) # Match image behavior: if self.extent is None: x0, x1, y0, y1 = (0, Nx, 0, Ny) else: x0, x1, y0, y1 = self.extent dx = float(x1 - x0) / Nx dy = float(y1 - y0) / Ny x = x0 + (arange(Nx) + 0.5) * dx y = y0 + (arange(Ny) + 0.5) * dy if self.origin == 'upper': y = y[::-1] return meshgrid(x, y)
def __init__(self, ax, labels, active=0, activecolor='blue'): """ Add radio buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings active is the index into labels for the button that is active activecolor is the color of the button when clicked """ self.activecolor = activecolor ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) dy = 1./(len(labels)+1) ys = linspace(1-dy, dy, len(labels)) cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.circles = [] for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') if cnt==active: facecolor = activecolor else: facecolor = axcolor p = Circle(xy=(0.15, y), radius=0.05, facecolor=facecolor, transform=ax.transAxes) self.labels.append(t) self.circles.append(p) ax.add_patch(p) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() vmin, vmax = self.viewInterval.get_bounds() if vmax < vmin: vmin, vmax = vmax, vmin if self.presets.has_key((vmin, vmax)): return self.presets[(vmin, vmax)] if self.numticks is None: self._set_numticks() if self.numticks == 0: return [] ticklocs = linspace(vmin, vmax, self.numticks) return ticklocs
def __call__(self): 'Return the locations of the ticks' self.verify_intervals() vmin, vmax = self.viewInterval.get_bounds() if vmax<vmin: vmin, vmax = vmax, vmin if self.presets.has_key((vmin, vmax)): return self.presets[(vmin, vmax)] if self.numticks is None: self._set_numticks() if self.numticks==0: return [] ticklocs = linspace(vmin, vmax, self.numticks) return ticklocs
def __init__(self, parent, handles, labels, loc, isaxes=True): Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error( 'Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' % (loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform(get_bbox_transform(unit_bbox(), parent.bbox)) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.NUMPOINTS == 1: self._xdata = array([left + self.HANDLELEN * 0.5]) else: self._xdata = linspace(left, left + self.HANDLELEN, self.NUMPOINTS) textleft = left + self.HANDLELEN + self.HANDLETEXTSEP self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top - HEIGHT left -= self.HANDLELEN + self.HANDLETEXTSEP + self.PAD self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT * len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def __init__(self, parent, handles, labels, loc, isaxes=True): Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error( "Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t" % (loc, "\n\t".join(self.codes.keys())) ) if is_string_like(loc): loc = self.codes.get(loc, 1) if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform(get_bbox_transform(unit_bbox(), parent.bbox)) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.NUMPOINTS == 1: self._xdata = array([left + self.HANDLELEN * 0.5]) else: self._xdata = linspace(left, left + self.HANDLELEN, self.NUMPOINTS) textleft = left + self.HANDLELEN + self.HANDLETEXTSEP self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top - HEIGHT left -= self.HANDLELEN + self.HANDLETEXTSEP + self.PAD self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT * len(self.texts), facecolor="w", edgecolor="k" ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def colorbar_classic(self, mappable, cax=None, orientation='vertical', tickfmt='%1.1f', cspacing='proportional', clabels=None, drawedges=False, edgewidth=0.5, edgecolor='k'): """ Create a colorbar for mappable image mappable is the cm.ScalarMappable instance that you want the colorbar to apply to, e.g. an Image as returned by imshow or a PatchCollection as returned by scatter or pcolor. tickfmt is a format string to format the colorbar ticks cax is a colorbar axes instance in which the colorbar will be placed. If None, as default axesd will be created resizing the current aqxes to make room for it. If not None, the supplied axes will be used and the other axes positions will be unchanged. orientation is the colorbar orientation: one of 'vertical' | 'horizontal' cspacing controls how colors are distributed on the colorbar. if cspacing == 'linear', each color occupies an equal area on the colorbar, regardless of the contour spacing. if cspacing == 'proportional' (Default), the area each color occupies on the the colorbar is proportional to the contour interval. Only relevant for a Contour image. clabels can be a sequence containing the contour levels to be labelled on the colorbar, or None (Default). If clabels is None, labels for all contour intervals are displayed. Only relevant for a Contour image. if drawedges == True, lines are drawn at the edges between each color on the colorbar. Default False. edgecolor is the line color delimiting the edges of the colors on the colorbar (if drawedges == True). Default black ('k') edgewidth is the width of the lines delimiting the edges of the colors on the colorbar (if drawedges == True). Default 0.5 return value is the colorbar axes instance """ if orientation not in ('horizontal', 'vertical'): raise ValueError('Orientation must be horizontal or vertical') if isinstance(mappable, FigureImage) and cax is None: raise TypeError('Colorbars for figure images currently not supported unless you provide a colorbar axes in cax') ax = self.gca() cmap = mappable.cmap if cax is None: l,b,w,h = ax.get_position() if orientation=='vertical': neww = 0.8*w ax.set_position((l,b,neww,h), 'both') cax = self.add_axes([l + 0.9*w, b, 0.1*w, h]) else: newh = 0.8*h ax.set_position((l,b+0.2*h,w,newh), 'both') cax = self.add_axes([l, b, w, 0.1*h]) else: if not isinstance(cax, Axes): raise TypeError('Expected an Axes instance for cax') norm = mappable.norm if norm.vmin is None or norm.vmax is None: mappable.autoscale() cmin = norm.vmin cmax = norm.vmax if isinstance(mappable, ContourSet): # mappable image is from contour or contourf clevs = mappable.levels clevs = minimum(clevs, cmax) clevs = maximum(clevs, cmin) isContourSet = True elif isinstance(mappable, ScalarMappable): # from imshow or pcolor. isContourSet = False clevs = linspace(cmin, cmax, cmap.N+1) # boundaries, hence N+1 else: raise TypeError("don't know how to handle type %s"%type(mappable)) N = len(clevs) C = array([clevs, clevs]) if cspacing == 'linear': X, Y = meshgrid(clevs, [0, 1]) elif cspacing == 'proportional': X, Y = meshgrid(linspace(cmin, cmax, N), [0, 1]) else: raise ValueError("cspacing must be 'linear' or 'proportional'") if orientation=='vertical': args = (transpose(Y), transpose(C), transpose(X), clevs) else: args = (C, Y, X, clevs) #If colors were listed in the original mappable, then # let contour handle them the same way. colors = getattr(mappable, 'colors', None) if colors is not None: kw = {'colors': colors} else: kw = {'cmap':cmap, 'norm':norm} if isContourSet and not mappable.filled: CS = cax.contour(*args, **kw) colls = mappable.collections for ii in range(len(colls)): CS.collections[ii].set_linewidth(colls[ii].get_linewidth()) else: kw['antialiased'] = False CS = cax.contourf(*args, **kw) if drawedges: for col in CS.collections: col.set_edgecolor(edgecolor) col.set_linewidth(edgewidth) mappable.add_observer(CS) mappable.set_colorbar(CS, cax) if isContourSet: if cspacing == 'linear': ticks = linspace(cmin, cmax, N) else: ticks = clevs if cmin == mappable.levels[0]: ticklevs = clevs else: # We are not showing the full ends of the range. ticks = ticks[1:-1] ticklevs = clevs[1:-1] labs = [tickfmt % lev for lev in ticklevs] if clabels is not None: for i, lev in enumerate(ticklevs): if lev not in clabels: labs[i] = '' if orientation=='vertical': cax.set_xticks([]) cax.yaxis.tick_right() cax.yaxis.set_label_position('right') if isContourSet: cax.set_yticks(ticks) cax.set_yticklabels(labs) else: cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt)) else: cax.set_yticks([]) if isContourSet: cax.set_xticks(ticks) cax.set_xticklabels(labs) else: cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt)) self.sca(ax) return cax
def __init__(self, parent, handles, labels, loc, isaxes=True, numpoints = 4, # the number of points in the legend line prop = FontProperties(size='smaller'), pad = 0.2, # the fractional whitespace inside the legend border markerscale = 0.6, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = 0.005, # the vertical space between the legend entries handlelen = 0.05, # the length of the legend lines handletextsep = 0.02, # the space between the legend line and legend text axespad = 0.02, # the border between the axes and legend edge shadow=False, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties('smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): verbose.report_error('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) self.numpoints = numpoints self.prop = prop self.fontsize = prop.get_size_in_points() self.pad = pad self.markerscale = markerscale self.labelsep = labelsep self.handlelen = handlelen self.handletextsep = handletextsep self.axespad = axespad self.shadow = shadow if isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, upper = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, upper) self.handles = self._get_handles(handles, self.texts) left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height() bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT*len(self.texts), facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def __init__(self, ax, labels, actives): """ Add check buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings actives is a len(buttons) list of booleans indicating whether the button is active """ ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if len(labels)>1: dy = 1./(len(labels)+1) ys = linspace(1-dy, dy, len(labels)) else: dy = 0.25 ys = [0.5] cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.lines = [] self.rectangles = [] lineparams = {'color':'k', 'linewidth':1.25, 'transform':ax.transAxes, 'solid_capstyle':'butt'} for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') w, h = dy/2., dy/2. x, y = 0.05, y-h/2. p = Rectangle(xy=(x,y), width=w, height=h, facecolor=axcolor, transform=ax.transAxes) l1 = Line2D([x, x+w], [y+h, y], **lineparams) l2 = Line2D([x, x+w], [y, y+h], **lineparams) l1.set_visible(actives[cnt]) l2.set_visible(actives[cnt]) self.labels.append(t) self.rectangles.append(p) self.lines.append((l1,l2)) ax.add_patch(p) ax.add_line(l1) ax.add_line(l2) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
def __init__(self, parent, handles, labels, loc, isaxes= None, numpoints = None, # the number of points in the legend line prop = None, pad = None, # the fractional whitespace inside the legend border markerscale = None, # the relative size of legend markers vs. original # the following dimensions are in axes coords labelsep = None, # the vertical space between the legend entries handlelen = None, # the length of the legend lines handletextsep = None, # the space between the legend line and legend text axespad = None, # the border between the axes and legend edge shadow= None, ): """ parent # the artist that contains the legend handles # a list of artists (lines, patches) to add to the legend labels # a list of strings to label the legend loc # a location code isaxes=True # whether this is an axes legend numpoints = 4 # the number of points in the legend line fontprop = FontProperties(size='smaller') # the font property pad = 0.2 # the fractional whitespace inside the legend border markerscale = 0.6 # the relative size of legend markers vs. original shadow # if True, draw a shadow behind legend The following dimensions are in axes coords labelsep = 0.005 # the vertical space between the legend entries handlelen = 0.05 # the length of the legend lines handletextsep = 0.02 # the space between the legend line and legend text axespad = 0.02 # the border between the axes and legend edge """ Artist.__init__(self) if is_string_like(loc) and not self.codes.has_key(loc): warnings.warn('Unrecognized location %s. Falling back on upper right; valid locations are\n%s\t' %(loc, '\n\t'.join(self.codes.keys()))) if is_string_like(loc): loc = self.codes.get(loc, 1) proplist=[numpoints, pad, markerscale, labelsep, handlelen, handletextsep, axespad, shadow, isaxes] propnames=['numpoints', 'pad', 'markerscale', 'labelsep', 'handlelen', 'handletextsep', 'axespad', 'shadow', 'isaxes'] for name, value in zip(propnames,proplist): if value is None: value=rcParams["legend."+name] setattr(self,name,value) if prop is None: self.prop=FontProperties(size=rcParams["legend.fontsize"]) else: self.prop=prop self.fontsize = self.prop.get_size_in_points() if self.isaxes: # parent is an Axes self.set_figure(parent.figure) else: # parent is a Figure self.set_figure(parent) self.parent = parent self.set_transform( get_bbox_transform( unit_bbox(), parent.bbox) ) self._loc = loc # make a trial box in the middle of the axes. relocate it # based on it's bbox left, top = 0.5, 0.5 if self.numpoints == 1: self._xdata = array([left + self.handlelen*0.5]) else: self._xdata = linspace(left, left + self.handlelen, self.numpoints) textleft = left+ self.handlelen+self.handletextsep self.texts = self._get_texts(labels, textleft, top) self.legendHandles = self._get_handles(handles, self.texts) if len(self.texts): left, top = self.texts[-1].get_position() HEIGHT = self._approx_text_height()*len(self.texts) else: HEIGHT = 0.2 bottom = top-HEIGHT left -= self.handlelen + self.handletextsep + self.pad self.legendPatch = Rectangle( xy=(left, bottom), width=0.5, height=HEIGHT, facecolor='w', edgecolor='k', ) self._set_artist_props(self.legendPatch) self._drawFrame = True
def __init__(self, ax, labels, actives): """ Add check buttons to axes.Axes instance ax labels is a len(buttons) list of labels as strings actives is a len(buttons) list of booleans indicating whether the button is active """ ax.set_xticks([]) ax.set_yticks([]) ax.set_navigate(False) if len(labels) > 1: dy = 1. / (len(labels) + 1) ys = linspace(1 - dy, dy, len(labels)) else: dy = 0.25 ys = [0.5] cnt = 0 axcolor = ax.get_axis_bgcolor() self.labels = [] self.lines = [] self.rectangles = [] lineparams = { 'color': 'k', 'linewidth': 1.25, 'transform': ax.transAxes, 'solid_capstyle': 'butt' } for y, label in zip(ys, labels): t = ax.text(0.25, y, label, transform=ax.transAxes, horizontalalignment='left', verticalalignment='center') w, h = dy / 2., dy / 2. x, y = 0.05, y - h / 2. p = Rectangle(xy=(x, y), width=w, height=h, facecolor=axcolor, transform=ax.transAxes) l1 = Line2D([x, x + w], [y + h, y], **lineparams) l2 = Line2D([x, x + w], [y, y + h], **lineparams) l1.set_visible(actives[cnt]) l2.set_visible(actives[cnt]) self.labels.append(t) self.rectangles.append(p) self.lines.append((l1, l2)) ax.add_patch(p) ax.add_line(l1) ax.add_line(l2) cnt += 1 ax.figure.canvas.mpl_connect('button_press_event', self._clicked) self.ax = ax self.cnt = 0 self.observers = {}
def colorbar_classic(self, mappable, cax=None, orientation='vertical', tickfmt='%1.1f', cspacing='proportional', clabels=None, drawedges=False, edgewidth=0.5, edgecolor='k'): """ Create a colorbar for mappable image mappable is the cm.ScalarMappable instance that you want the colorbar to apply to, e.g. an Image as returned by imshow or a PatchCollection as returned by scatter or pcolor. tickfmt is a format string to format the colorbar ticks cax is a colorbar axes instance in which the colorbar will be placed. If None, as default axesd will be created resizing the current aqxes to make room for it. If not None, the supplied axes will be used and the other axes positions will be unchanged. orientation is the colorbar orientation: one of 'vertical' | 'horizontal' cspacing controls how colors are distributed on the colorbar. if cspacing == 'linear', each color occupies an equal area on the colorbar, regardless of the contour spacing. if cspacing == 'proportional' (Default), the area each color occupies on the the colorbar is proportional to the contour interval. Only relevant for a Contour image. clabels can be a sequence containing the contour levels to be labelled on the colorbar, or None (Default). If clabels is None, labels for all contour intervals are displayed. Only relevant for a Contour image. if drawedges == True, lines are drawn at the edges between each color on the colorbar. Default False. edgecolor is the line color delimiting the edges of the colors on the colorbar (if drawedges == True). Default black ('k') edgewidth is the width of the lines delimiting the edges of the colors on the colorbar (if drawedges == True). Default 0.5 return value is the colorbar axes instance """ if orientation not in ('horizontal', 'vertical'): raise ValueError('Orientation must be horizontal or vertical') if isinstance(mappable, FigureImage) and cax is None: raise TypeError( 'Colorbars for figure images currently not supported unless you provide a colorbar axes in cax' ) ax = self.gca() cmap = mappable.cmap if cax is None: l, b, w, h = ax.get_position() if orientation == 'vertical': neww = 0.8 * w ax.set_position((l, b, neww, h), 'both') cax = self.add_axes([l + 0.9 * w, b, 0.1 * w, h]) else: newh = 0.8 * h ax.set_position((l, b + 0.2 * h, w, newh), 'both') cax = self.add_axes([l, b, w, 0.1 * h]) else: if not isinstance(cax, Axes): raise TypeError('Expected an Axes instance for cax') norm = mappable.norm if norm.vmin is None or norm.vmax is None: mappable.autoscale() cmin = norm.vmin cmax = norm.vmax if isinstance(mappable, ContourSet): # mappable image is from contour or contourf clevs = mappable.levels clevs = minimum(clevs, cmax) clevs = maximum(clevs, cmin) isContourSet = True elif isinstance(mappable, ScalarMappable): # from imshow or pcolor. isContourSet = False clevs = linspace(cmin, cmax, cmap.N + 1) # boundaries, hence N+1 else: raise TypeError("don't know how to handle type %s" % type(mappable)) N = len(clevs) C = array([clevs, clevs]) if cspacing == 'linear': X, Y = meshgrid(clevs, [0, 1]) elif cspacing == 'proportional': X, Y = meshgrid(linspace(cmin, cmax, N), [0, 1]) else: raise ValueError("cspacing must be 'linear' or 'proportional'") if orientation == 'vertical': args = (transpose(Y), transpose(C), transpose(X), clevs) else: args = (C, Y, X, clevs) #If colors were listed in the original mappable, then # let contour handle them the same way. colors = getattr(mappable, 'colors', None) if colors is not None: kw = {'colors': colors} else: kw = {'cmap': cmap, 'norm': norm} if isContourSet and not mappable.filled: CS = cax.contour(*args, **kw) colls = mappable.collections for ii in range(len(colls)): CS.collections[ii].set_linewidth(colls[ii].get_linewidth()) else: kw['antialiased'] = False CS = cax.contourf(*args, **kw) if drawedges: for col in CS.collections: col.set_edgecolor(edgecolor) col.set_linewidth(edgewidth) mappable.add_observer(CS) mappable.set_colorbar(CS, cax) if isContourSet: if cspacing == 'linear': ticks = linspace(cmin, cmax, N) else: ticks = clevs if cmin == mappable.levels[0]: ticklevs = clevs else: # We are not showing the full ends of the range. ticks = ticks[1:-1] ticklevs = clevs[1:-1] labs = [tickfmt % lev for lev in ticklevs] if clabels is not None: for i, lev in enumerate(ticklevs): if lev not in clabels: labs[i] = '' if orientation == 'vertical': cax.set_xticks([]) cax.yaxis.tick_right() cax.yaxis.set_label_position('right') if isContourSet: cax.set_yticks(ticks) cax.set_yticklabels(labs) else: cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt)) else: cax.set_yticks([]) if isContourSet: cax.set_xticks(ticks) cax.set_xticklabels(labs) else: cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt)) self.sca(ax) return cax
def colorbar(self, mappable, tickfmt='%1.1f', cax=None, orientation='vertical'): """ Create a colorbar for mappable image tickfmt is a format string to format the colorbar ticks cax is a colorbar axes instance in which the colorbar will be placed. If None, as default axesd will be created resizing the current aqxes to make room for it. If not None, the supplied axes will be used and the other axes positions will be unchanged. orientation is the colorbar orientation: one of 'vertical' | 'horizontal' return value is the colorbar axes instance """ if orientation not in ('horizontal', 'vertical'): raise ValueError('Orientation must be horizontal or vertical') if isinstance(mappable, FigureImage) and cax is None: raise TypeError( 'Colorbars for figure images currently not supported unless you provide a colorbar axes in cax' ) ax = self.gca() cmap = mappable.cmap norm = mappable.norm if norm.vmin is None or norm.vmax is None: mappable.autoscale() cmin = norm.vmin cmax = norm.vmax if cax is None: l, b, w, h = ax.get_position() if orientation == 'vertical': neww = 0.8 * w ax.set_position((l, b, neww, h)) cax = self.add_axes([l + 0.9 * w, b, 0.1 * w, h]) else: newh = 0.8 * h ax.set_position((l, b + 0.2 * h, w, newh)) cax = self.add_axes([l, b, w, 0.1 * h]) else: if not isinstance(cax, Axes): raise TypeError('Expected an Axes instance for cax') N = cmap.N c = linspace(cmin, cmax, N) C = array([c, c]) if orientation == 'vertical': C = transpose(C) if orientation == 'vertical': extent = (0, 1, cmin, cmax) else: extent = (cmin, cmax, 0, 1) coll = cax.imshow(C, interpolation='nearest', origin='lower', cmap=cmap, norm=norm, extent=extent) mappable.add_observer(coll) mappable.set_colorbar(coll, cax) if orientation == 'vertical': cax.set_xticks([]) cax.yaxis.tick_right() cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt)) else: cax.set_yticks([]) cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt)) self.sca(ax) return cax
def colorbar(self, mappable, tickfmt='%1.1f', cax=None, orientation='vertical'): """ Create a colorbar for mappable image tickfmt is a format string to format the colorbar ticks cax is a colorbar axes instance in which the colorbar will be placed. If None, as default axesd will be created resizing the current aqxes to make room for it. If not None, the supplied axes will be used and the other axes positions will be unchanged. orientation is the colorbar orientation: one of 'vertical' | 'horizontal' return value is the colorbar axes instance """ if orientation not in ('horizontal', 'vertical'): raise ValueError('Orientation must be horizontal or vertical') if isinstance(mappable, FigureImage) and cax is None: raise TypeError('Colorbars for figure images currently not supported unless you provide a colorbar axes in cax') ax = self.gca() cmap = mappable.cmap norm = mappable.norm if norm.vmin is None or norm.vmax is None: mappable.autoscale() cmin = norm.vmin cmax = norm.vmax if cax is None: l,b,w,h = ax.get_position() if orientation=='vertical': neww = 0.8*w ax.set_position((l,b,neww,h)) cax = self.add_axes([l + 0.9*w, b, 0.1*w, h]) else: newh = 0.8*h ax.set_position((l,b+0.2*h,w,newh)) cax = self.add_axes([l, b, w, 0.1*h]) else: if not isinstance(cax, Axes): raise TypeError('Expected an Axes instance for cax') N = cmap.N c = linspace(cmin, cmax, N) C = array([c,c]) if orientation=='vertical': C = transpose(C) if orientation=='vertical': extent=(0, 1, cmin, cmax) else: extent=(cmin, cmax, 0, 1) coll = cax.imshow(C, interpolation='nearest', #interpolation='bilinear', origin='lower', cmap=cmap, norm=norm, extent=extent) mappable.add_observer(coll) mappable.set_colorbar(coll, cax) if orientation=='vertical': cax.set_xticks([]) cax.yaxis.tick_right() cax.yaxis.set_major_formatter(FormatStrFormatter(tickfmt)) else: cax.set_yticks([]) cax.xaxis.set_major_formatter(FormatStrFormatter(tickfmt)) self.sca(ax) return cax