def map_to_colors(buff, cmap_name): try: lut = cmd.color_map_luts[cmap_name] except KeyError as e: try: # if cmap is tuple, then we're using palettable or brewer2mpl cmaps if isinstance(cmap_name, tuple): cmap = get_brewer_cmap(cmap_name) else: cmap = mcm.get_cmap(cmap_name) cmap(0.0) lut = cmap._lut.T except ValueError: raise KeyError( "Your color map (%s) was not found in either the extracted" " colormap file or matplotlib colormaps" % cmap_name) from e if isinstance(cmap_name, tuple): # If we are using the colorbrewer maps, don't interpolate shape = buff.shape # We add float_eps so that digitize doesn't go out of bounds x = np.mgrid[0.0:1.0 + np.finfo(np.float32).eps:lut[0].shape[0] * 1j] inds = np.digitize(buff.ravel(), x) inds.shape = (shape[0], shape[1]) mapped = np.dstack([(v[inds] * 255).astype("uint8") for v in lut]) del inds else: x = np.mgrid[0.0:1.0:lut[0].shape[0] * 1j] mapped = np.dstack([(np.interp(buff, x, v) * 255).astype("uint8") for v in lut]) return mapped.copy("C")
def get_colormap_lut(cmap_id: Union[Tuple[str, str], str]): # "lut" stands for "lookup table". This function provides a consistent and # reusable accessor to a hidden (and by defaut, uninitialized) attribute # (`_lut`) in registered colormaps, from matplotlib or palettable. # colormap "lookup tables" are RGBA arrays in matplotlib, # and contain sufficient data to reconstruct the colormaps entierly. # This exists mostly for historical reasons, hence the custom output format. # It isn't meant as part of yt's public api. if isinstance(cmap_id, tuple) and len(cmap_id) == 2: cmap = get_brewer_cmap(cmap_id) elif isinstance(cmap_id, str): cmap = get_cmap(cmap_id) else: raise TypeError( "Expected a string or a 2-tuple of strings as a colormap id. " f"Received: {cmap_id}" ) if not cmap._isinit: cmap._init() r = cmap._lut[:-3, 0] g = cmap._lut[:-3, 1] b = cmap._lut[:-3, 2] a = np.ones(b.shape) return [r, g, b, a]
def _init_image(self, data, cbnorm, cblinthresh, cmap, extent, aspect): """Store output of imshow in image variable""" if (cbnorm == 'log10'): norm = matplotlib.colors.LogNorm() elif (cbnorm == 'linear'): norm = matplotlib.colors.Normalize() elif (cbnorm == 'symlog'): if cblinthresh is None: cblinthresh = float((np.nanmax(data) - np.nanmin(data)) / 10.) norm = matplotlib.colors.SymLogNorm(cblinthresh, vmin=float(np.nanmin(data)), vmax=float(np.nanmax(data))) extent = [float(e) for e in extent] # tuple colormaps are from palettable (or brewer2mpl) if isinstance(cmap, tuple): cmap = get_brewer_cmap(cmap) vmin = float(self.zmin) if self.zmax is not None else None vmax = float(self.zmax) if self.zmax is not None else None self.image = self.axes.imshow(data.to_ndarray(), origin='lower', extent=extent, norm=norm, vmin=vmin, vmax=vmax, aspect=aspect, cmap=cmap, interpolation='nearest') if (cbnorm == 'symlog'): if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"): formatter_kwargs = {} else: formatter_kwargs = dict(linthresh=cblinthresh) formatter = matplotlib.ticker.LogFormatterMathtext( **formatter_kwargs) self.cb = self.figure.colorbar(self.image, self.cax, format=formatter) if np.nanmin(data) >= 0.0: yticks = [np.nanmin(data).v] + list(10**np.arange( np.rint(np.log10(cblinthresh)), np.ceil(np.log10(np.nanmax(data))) + 1)) elif np.nanmax(data) <= 0.0: yticks = list( -10**np.arange( np.floor(np.log10(-np.nanmin(data))), np.rint(np.log10(cblinthresh)) - 1, -1)) + \ [np.nanmax(data).v] else: yticks = list( -10**np.arange(np.floor(np.log10(-np.nanmin(data))), np.rint(np.log10(cblinthresh))-1, -1)) + \ [0] + \ list(10**np.arange(np.rint(np.log10(cblinthresh)), np.ceil(np.log10(np.nanmax(data)))+1)) self.cb.set_ticks(yticks) else: self.cb = self.figure.colorbar(self.image, self.cax) for which in ['major', 'minor']: self.cax.tick_params(which=which, axis='y', direction='in')
def _init_image(self, data, cbnorm, cblinthresh, cmap, extent, aspect): """Store output of imshow in image variable""" cbnorm_kwargs = dict( vmin=float(self.zmin) if self.zmin is not None else None, vmax=float(self.zmax) if self.zmax is not None else None, ) if cbnorm == "log10": cbnorm_cls = matplotlib.colors.LogNorm elif cbnorm == "linear": cbnorm_cls = matplotlib.colors.Normalize elif cbnorm == "symlog": if cblinthresh is None: cblinthresh = float((np.nanmax(data) - np.nanmin(data)) / 10.0) cbnorm_kwargs.update( dict( linthresh=cblinthresh, vmin=float(np.nanmin(data)), vmax=float(np.nanmax(data)), )) MPL_VERSION = LooseVersion(matplotlib.__version__) if MPL_VERSION >= "3.2.0": # note that this creates an inconsistency between mpl versions # since the default value previous to mpl 3.4.0 is np.e # but it is only exposed since 3.2.0 cbnorm_kwargs["base"] = 10 cbnorm_cls = matplotlib.colors.SymLogNorm else: raise ValueError(f"Unknown value `cbnorm` == {cbnorm}") norm = cbnorm_cls(**cbnorm_kwargs) extent = [float(e) for e in extent] # tuple colormaps are from palettable (or brewer2mpl) if isinstance(cmap, tuple): cmap = get_brewer_cmap(cmap) if self._transform is None: # sets the transform to be an ax.TransData object, where the # coordiante system of the data is controlled by the xlim and ylim # of the data. transform = self.axes.transData else: transform = self._transform if hasattr(self.axes, "set_extent"): # CartoPy hangs if we do not set_extent before imshow if we are # displaying a small subset of the globe. What I believe happens is # that the transform for the points on the outside results in # infinities, and then the scipy.spatial cKDTree hangs trying to # identify nearest points. # # Also, set_extent is defined by cartopy, so not all axes will have # it as a method. # # A potential downside is that other images may change, but I believe # the result of imshow is to set_extent *regardless*. This just # changes the order in which it happens. # # NOTE: This is currently commented out because it breaks in some # instances. It is left as a historical note because we will # eventually need some form of it. # self.axes.set_extent(extent) pass self.image = self.axes.imshow( data.to_ndarray(), origin="lower", extent=extent, norm=norm, aspect=aspect, cmap=cmap, interpolation="nearest", transform=transform, ) if cbnorm == "symlog": if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"): formatter_kwargs = {} else: formatter_kwargs = dict(linthresh=cblinthresh) formatter = matplotlib.ticker.LogFormatterMathtext( **formatter_kwargs) self.cb = self.figure.colorbar(self.image, self.cax, format=formatter) if np.nanmin(data) >= 0.0: yticks = [np.nanmin(data).v] + list(10**np.arange( np.rint(np.log10(cblinthresh)), np.ceil(np.log10(np.nanmax(data))) + 1, )) elif np.nanmax(data) <= 0.0: yticks = list(-(10**np.arange( np.floor(np.log10(-np.nanmin(data))), np.rint(np.log10(cblinthresh)) - 1, -1, ))) + [np.nanmax(data).v] else: yticks = (list(-(10**np.arange( np.floor(np.log10(-np.nanmin(data))), np.rint(np.log10(cblinthresh)) - 1, -1, ))) + [0] + list(10**np.arange( np.rint(np.log10(cblinthresh)), np.ceil(np.log10(np.nanmax(data))) + 1, ))) self.cb.set_ticks(yticks) else: self.cb = self.figure.colorbar(self.image, self.cax) for which in ["major", "minor"]: self.cax.tick_params(which=which, axis="y", direction="in")
def _init_image(self, data, cbnorm, cblinthresh, cmap, extent, aspect): """Store output of imshow in image variable""" cbnorm_kwargs = dict( vmin=float(self.zmin) if self.zmin is not None else None, vmax=float(self.zmax) if self.zmax is not None else None, ) zmin = float(self.zmin) if self.zmin is not None else np.nanmin(data) zmax = float(self.zmax) if self.zmax is not None else np.nanmax(data) if cbnorm == "symlog": # if cblinthresh is not specified, try to come up with a reasonable default min_abs_val = np.min(np.abs((zmin, zmax))) if cblinthresh is None: cblinthresh = np.nanmin(np.absolute(data)[data != 0]) elif zmin * zmax > 0 and cblinthresh < min_abs_val: warnings.warn( f"Cannot set a symlog norm with linear threshold {cblinthresh} " f"lower than the minimal absolute data value {min_abs_val} . " "Switching to log norm.") cbnorm = "log10" if cbnorm == "log10": cbnorm_cls = matplotlib.colors.LogNorm elif cbnorm == "linear": cbnorm_cls = matplotlib.colors.Normalize elif cbnorm == "symlog": cbnorm_kwargs.update(dict(linthresh=cblinthresh)) if MPL_VERSION >= Version("3.2.0"): # note that this creates an inconsistency between mpl versions # since the default value previous to mpl 3.4.0 is np.e # but it is only exposed since 3.2.0 cbnorm_kwargs["base"] = 10 cbnorm_cls = matplotlib.colors.SymLogNorm else: raise ValueError(f"Unknown value `cbnorm` == {cbnorm}") norm = cbnorm_cls(**cbnorm_kwargs) extent = [float(e) for e in extent] # tuple colormaps are from palettable (or brewer2mpl) if isinstance(cmap, tuple): cmap = get_brewer_cmap(cmap) if self._transform is None: # sets the transform to be an ax.TransData object, where the # coordinate system of the data is controlled by the xlim and ylim # of the data. transform = self.axes.transData else: transform = self._transform if hasattr(self.axes, "set_extent"): # CartoPy hangs if we do not set_extent before imshow if we are # displaying a small subset of the globe. What I believe happens is # that the transform for the points on the outside results in # infinities, and then the scipy.spatial cKDTree hangs trying to # identify nearest points. # # Also, set_extent is defined by cartopy, so not all axes will have # it as a method. # # A potential downside is that other images may change, but I believe # the result of imshow is to set_extent *regardless*. This just # changes the order in which it happens. # # NOTE: This is currently commented out because it breaks in some # instances. It is left as a historical note because we will # eventually need some form of it. # self.axes.set_extent(extent) # possibly related issue (operation order dependency) # https://github.com/SciTools/cartopy/issues/1468 # in cartopy 0.19 (or 0.20), some intented behaviour changes produced an # incompatibility here where default values for extent would lead to a crash. # A solution is to let the transform object set the image extents internally # see https://github.com/SciTools/cartopy/issues/1955 extent = None self.image = self.axes.imshow( data.to_ndarray(), origin="lower", extent=extent, norm=norm, aspect=aspect, cmap=cmap, interpolation="nearest", transform=transform, ) if cbnorm == "symlog": formatter = matplotlib.ticker.LogFormatterMathtext( linthresh=cblinthresh) self.cb = self.figure.colorbar(self.image, self.cax, format=formatter) if zmin >= 0.0: yticks = [zmin] + list(10**np.arange( np.rint(np.log10(cblinthresh)), np.ceil(np.log10(zmax)), )) elif zmax <= 0.0: if MPL_VERSION >= Version("3.5.0b"): offset = 0 else: offset = 1 yticks = (list(-(10**np.arange( np.floor(np.log10(-zmin)), np.rint(np.log10(cblinthresh)) - offset, -1, ))) + [zmax]) else: yticks = (list(-(10**np.arange( np.floor(np.log10(-zmin)), np.rint(np.log10(cblinthresh)) - 1, -1, ))) + [0] + list(10**np.arange( np.rint(np.log10(cblinthresh)), np.ceil(np.log10(zmax)), ))) self.cb.set_ticks(yticks) else: self.cb = self.figure.colorbar(self.image, self.cax) self.cax.tick_params(which="both", axis="y", direction="in")
def _init_image(self, data, cbnorm, cblinthresh, cmap, extent, aspect): """Store output of imshow in image variable""" if (cbnorm == 'log10'): norm = matplotlib.colors.LogNorm() elif (cbnorm == 'linear'): norm = matplotlib.colors.Normalize() elif (cbnorm == 'symlog'): if cblinthresh is None: cblinthresh = float((np.nanmax(data)-np.nanmin(data))/10.) norm = matplotlib.colors.SymLogNorm( cblinthresh, vmin=float(np.nanmin(data)), vmax=float(np.nanmax(data))) extent = [float(e) for e in extent] # tuple colormaps are from palettable (or brewer2mpl) if isinstance(cmap, tuple): cmap = get_brewer_cmap(cmap) vmin = float(self.zmin) if self.zmax is not None else None vmax = float(self.zmax) if self.zmax is not None else None if self._transform is None: # sets the transform to be an ax.TransData object, where the # coordiante system of the data is controlled by the xlim and ylim # of the data. transform = self.axes.transData else: transform = self._transform if hasattr(self.axes, "set_extent"): # CartoPy hangs if we do not set_extent before imshow if we are # displaying a small subset of the globe. What I believe happens is # that the transform for the points on the outside results in # infinities, and then the scipy.spatial cKDTree hangs trying to # identify nearest points. # # Also, set_extent is defined by cartopy, so not all axes will have # it as a method. # # A potential downside is that other images may change, but I believe # the result of imshow is to set_extent *regardless*. This just # changes the order in which it happens. # # NOTE: This is currently commented out because it breaks in some # instances. It is left as a historical note because we will # eventually need some form of it. # self.axes.set_extent(extent) pass self.image = self.axes.imshow( data.to_ndarray(), origin='lower', extent=extent, norm=norm, vmin=vmin, vmax=vmax, aspect=aspect, cmap=cmap, interpolation='nearest', transform=transform) if (cbnorm == 'symlog'): if LooseVersion(matplotlib.__version__) < LooseVersion("2.0.0"): formatter_kwargs = {} else: formatter_kwargs = dict(linthresh=cblinthresh) formatter = matplotlib.ticker.LogFormatterMathtext( **formatter_kwargs) self.cb = self.figure.colorbar( self.image, self.cax, format=formatter) if np.nanmin(data) >= 0.0: yticks = [np.nanmin(data).v] + list( 10**np.arange(np.rint(np.log10(cblinthresh)), np.ceil(np.log10(np.nanmax(data))) + 1)) elif np.nanmax(data) <= 0.0: yticks = list( -10**np.arange( np.floor(np.log10(-np.nanmin(data))), np.rint(np.log10(cblinthresh)) - 1, -1)) + \ [np.nanmax(data).v] else: yticks = list( -10**np.arange(np.floor(np.log10(-np.nanmin(data))), np.rint(np.log10(cblinthresh))-1, -1)) + \ [0] + \ list(10**np.arange(np.rint(np.log10(cblinthresh)), np.ceil(np.log10(np.nanmax(data)))+1)) self.cb.set_ticks(yticks) else: self.cb = self.figure.colorbar(self.image, self.cax) for which in ['major', 'minor']: self.cax.tick_params(which=which, axis='y', direction='in')