""" Builtin colormaps, colormap handling utilities, and the `ScalarMappable` mixin.
.. seealso::
:doc:`/gallery/color/colormap_reference` for a list of builtin colormaps.
:doc:`/tutorials/colors/colormap-manipulation` for examples of how to make colormaps and
:doc:`/tutorials/colors/colormaps` an in-depth discussion of choosing colormaps.
:doc:`/tutorials/colors/colormapnorms` for more details about data normalization
"""
# reverse all the colormaps. # reversed colormaps have '_r' appended to the name.
"""Helper such that ``_reverser(f)(x) == f(1 - x)``.""" # Returning a partial object keeps it picklable. return f(1 - x)
"""Can only handle specification *data* in dictionary format.""" # This doesn't work: lambda x: val(1-x) # The same "val" (the first one) is used # each time, so the colors are identical # and the result is shades of gray. else: # Flip x and exchange the y values facing x = 0 and x = 1.
"""Reverses cmap specification *spec*, can handle both dict and tuple type specs."""
else:
"""Generates the requested cmap from its *name*. The lut size is *lutsize*."""
# Generate the colormap object. else:
# Generate the reversed specifications (all at once, to avoid # modify-when-iterating). for cmapname, spec in datad.items()})
# Precache the cmaps with ``lutsize = LUTSIZE``. # Also add the reversed ones added in the section above:
# Continue with definitions ...
""" Add a colormap to the set recognized by :func:`get_cmap`.
It can be used in two ways::
register_cmap(name='swirly', cmap=swirly_cmap)
register_cmap(name='choppy', data=choppydata, lut=128)
In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap` instance. The *name* is optional; if absent, the name will be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.
In the second case, the three arguments are passed to the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer, and the resulting colormap is registered.
""" if name is None: try: name = cmap.name except AttributeError: raise ValueError("Arguments must include a name or a Colormap")
if not isinstance(name, str): raise ValueError("Colormap name must be a string")
if isinstance(cmap, colors.Colormap): cmap_d[name] = cmap return
# For the remainder, let exceptions propagate. if lut is None: lut = mpl.rcParams['image.lut'] cmap = colors.LinearSegmentedColormap(name, data, lut) cmap_d[name] = cmap
""" Get a colormap instance, defaulting to rc values if *name* is None.
Colormaps added with :func:`register_cmap` take precedence over built-in colormaps.
If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be returned.
If *lut* is not None it must be an integer giving the number of entries desired in the lookup table, and *name* must be a standard mpl colormap name. """
else: return cmap_d[name]._resample(lut) else: raise ValueError( "Colormap %s is not recognized. Possible values are: %s" % (name, ', '.join(sorted(cmap_d))))
""" This is a mixin class to support scalar data to RGBA mapping. The ScalarMappable makes use of data normalization before returning RGBA colors from the given colormap.
""" r"""
Parameters ---------- norm : :class:`matplotlib.colors.Normalize` instance The normalizing object which scales data, typically into the interval ``[0, 1]``. If *None*, *norm* defaults to a *colors.Normalize* object which initializes its scaling based on the first data processed. cmap : str or :class:`~matplotlib.colors.Colormap` instance The colormap used to map normalized data values to RGBA colors. """
#: The Normalization instance of this ScalarMappable. #: The Colormap instance of this ScalarMappable. #: The last colorbar associated with this ScalarMappable. May be None.
""" Return a normalized rgba array corresponding to *x*.
In the normal case, *x* is a 1-D or 2-D sequence of scalars, and the corresponding ndarray of rgba values will be returned, based on the norm and colormap set for this ScalarMappable.
There is one special case, for handling images that are already rgb or rgba, such as might have been read from an image file. If *x* is an ndarray with 3 dimensions, and the last dimension is either 3 or 4, then it will be treated as an rgb or rgba array, and no mapping will be done. The array can be uint8, or it can be floating point with values in the 0-1 range; otherwise a ValueError will be raised. If it is a masked array, the mask will be ignored. If the last dimension is 3, the *alpha* kwarg (defaulting to 1) will be used to fill in the transparency. If the last dimension is 4, the *alpha* kwarg is ignored; it does not replace the pre-existing alpha. A ValueError will be raised if the third dimension is other than 3 or 4.
In either case, if *bytes* is *False* (default), the rgba array will be floats in the 0-1 range; if it is *True*, the returned rgba array will be uint8 in the 0 to 255 range.
If norm is False, no normalization of the input data is performed, and it is assumed to be in the range (0-1).
""" # First check for special case, image input: if alpha is None: alpha = 1 if x.dtype == np.uint8: alpha = np.uint8(alpha * 255) m, n = x.shape[:2] xx = np.empty(shape=(m, n, 4), dtype=x.dtype) xx[:, :, :3] = x xx[:, :, 3] = alpha else: raise ValueError("third dimension must be 3 or 4") raise ValueError("Floating point image RGB values " "must be in the 0..1 range.") elif xx.dtype == np.uint8: if not bytes: xx = xx.astype(np.float32) / 255 else: raise ValueError("Image RGB array must be uint8 or " "floating point; found %s" % xx.dtype) # e.g., x is not an ndarray; so try mapping it
# This is the normal case, mapping a scalar array:
"""Set the image array from numpy array *A*.
Parameters ---------- A : ndarray """
'Return the array'
'return the colormap' return self.cmap
'return the min, max of the color limits for image scaling' return self.norm.vmin, self.norm.vmax
""" set the norm limits for image scaling; if *vmin* is a length2 sequence, interpret it as ``(vmin, vmax)`` which is used to support setp
ACCEPTS: a length 2 sequence of floats; may be overridden in methods that have ``vmin`` and ``vmax`` kwargs. """
""" set the colormap for luminance data
Parameters ---------- cmap : colormap or registered colormap name """
"""Set the normalization instance.
Parameters ---------- norm : `.Normalize` """
""" Autoscale the scalar limits on the norm instance using the current array """ if self._A is None: raise TypeError('You must first set_array for mappable') self.norm.autoscale(self._A) self.changed()
""" Autoscale the scalar limits on the norm instance using the current array, changing only limits that are None """ raise TypeError('You must first set_array for mappable')
""" Add an entry to a dictionary of boolean flags that are set to True when the mappable is changed. """ self.update_dict[checker] = False
""" If mappable has changed since the last check, return True; else return False """ return False
""" Call this whenever the mappable is changed to notify all the callbackSM listeners to the 'changed' signal """
|