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 len(shape(z)) != 2: raise TypeError("Input must be a 2D array.") else: Ny, Nx = shape(z) if self.origin is None: return meshgrid(arange(Nx), arange(Ny)) 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, origin, extent): ''' 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 len(shape(z)) != 2: raise TypeError("Input must be a 2D array.") else: Ny, Nx = shape(z) if origin is None: return meshgrid(arange(Nx), arange(Ny)) if extent is None: x0, x1, y0, y1 = (0, Nx, 0, Ny) else: x0, x1, y0, y1 = 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 origin == 'upper': y = y[::-1] return meshgrid(x, y)
def _check_xyz(self, args): ''' For functions like contour, check that the dimensions of the input arrays match; if x and y are 1D, convert them to 2D using meshgrid. Possible change: I think we should make and use an ArgumentError Exception class (here and elsewhere). ''' x, y, z = args if len(shape(z)) != 2: raise TypeError("Input z must be a 2D array.") else: Ny, Nx = shape(z) if shape(x) == shape(z) and shape(y) == shape(z): return x, y, z if len(shape(x)) != 1 or len(shape(y)) != 1: raise TypeError("Inputs x and y must be 1D or 2D.") nx, = shape(x) ny, = shape(y) if nx != Nx or ny != Ny: raise TypeError("Length of x must be number of columns in z,\n" + "and length of y must be number of rows.") x, y = meshgrid(x, y) return x, y, z
def _check_xyz(self, args): ''' For functions like contour, check that the dimensions of the input arrays match; if x and y are 1D, convert them to 2D using meshgrid. Possible change: I think we should make and use an ArgumentError Exception class (here and elsewhere). Add checking for everything being the same numerix flavor? ''' x,y,z = args if len(shape(z)) != 2: raise TypeError("Input z must be a 2D array.") else: Ny, Nx = shape(z) if shape(x) == shape(z) and shape(y) == shape(z): return x,y,z if len(shape(x)) != 1 or len(shape(y)) != 1: raise TypeError("Inputs x and y must be 1D or 2D.") nx, = shape(x) ny, = shape(y) if nx != Nx or ny != Ny: raise TypeError("Length of x must be number of columns in z,\n" + "and length of y must be number of rows.") x,y = meshgrid(x,y) return x,y,z
def get_test_data(delta=0.05): from mlab import meshgrid, bivariate_normal x = y = nx.arange(-3.0, 3.0, delta) X, Y = meshgrid(x,y) Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = Z2-Z1 X = X * 10 Y = Y * 10 Z = Z * 500 return X,Y,Z
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 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_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