cm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. """
  2. Builtin colormaps, colormap handling utilities, and the `ScalarMappable` mixin.
  3. .. seealso::
  4. :doc:`/gallery/color/colormap_reference` for a list of builtin colormaps.
  5. :doc:`/tutorials/colors/colormap-manipulation` for examples of how to
  6. make colormaps.
  7. :doc:`/tutorials/colors/colormaps` an in-depth discussion of
  8. choosing colormaps.
  9. :doc:`/tutorials/colors/colormapnorms` for more details about data
  10. normalization.
  11. """
  12. import functools
  13. import numpy as np
  14. from numpy import ma
  15. import matplotlib as mpl
  16. import matplotlib.colors as colors
  17. import matplotlib.cbook as cbook
  18. from matplotlib._cm import datad
  19. from matplotlib._cm_listed import cmaps as cmaps_listed
  20. def _reverser(f, x): # Deprecated, remove this at the same time as revcmap.
  21. return f(1 - x) # Toplevel helper for revcmap ensuring cmap picklability.
  22. @cbook.deprecated("3.2", alternative="Colormap.reversed()")
  23. def revcmap(data):
  24. """Can only handle specification *data* in dictionary format."""
  25. data_r = {}
  26. for key, val in data.items():
  27. if callable(val):
  28. # Return a partial object so that the result is picklable.
  29. valnew = functools.partial(_reverser, val)
  30. else:
  31. # Flip x and exchange the y values facing x = 0 and x = 1.
  32. valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)]
  33. data_r[key] = valnew
  34. return data_r
  35. LUTSIZE = mpl.rcParams['image.lut']
  36. def _gen_cmap_d():
  37. """
  38. Generate a dict mapping standard colormap names to standard colormaps, as
  39. well as the reversed colormaps.
  40. """
  41. cmap_d = {**cmaps_listed}
  42. for name, spec in datad.items():
  43. cmap_d[name] = ( # Precache the cmaps at a fixed lutsize..
  44. colors.LinearSegmentedColormap(name, spec, LUTSIZE)
  45. if 'red' in spec else
  46. colors.ListedColormap(spec['listed'], name)
  47. if 'listed' in spec else
  48. colors.LinearSegmentedColormap.from_list(name, spec, LUTSIZE))
  49. # Generate reversed cmaps.
  50. for cmap in list(cmap_d.values()):
  51. rmap = cmap.reversed()
  52. cmap_d[rmap.name] = rmap
  53. return cmap_d
  54. cmap_d = _gen_cmap_d()
  55. locals().update(cmap_d)
  56. # Continue with definitions ...
  57. def register_cmap(name=None, cmap=None, data=None, lut=None):
  58. """
  59. Add a colormap to the set recognized by :func:`get_cmap`.
  60. It can be used in two ways::
  61. register_cmap(name='swirly', cmap=swirly_cmap)
  62. register_cmap(name='choppy', data=choppydata, lut=128)
  63. In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
  64. instance. The *name* is optional; if absent, the name will
  65. be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.
  66. In the second case, the three arguments are passed to
  67. the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
  68. and the resulting colormap is registered.
  69. """
  70. cbook._check_isinstance((str, None), name=name)
  71. if name is None:
  72. try:
  73. name = cmap.name
  74. except AttributeError:
  75. raise ValueError("Arguments must include a name or a Colormap")
  76. if isinstance(cmap, colors.Colormap):
  77. cmap_d[name] = cmap
  78. return
  79. # For the remainder, let exceptions propagate.
  80. if lut is None:
  81. lut = mpl.rcParams['image.lut']
  82. cmap = colors.LinearSegmentedColormap(name, data, lut)
  83. cmap_d[name] = cmap
  84. def get_cmap(name=None, lut=None):
  85. """
  86. Get a colormap instance, defaulting to rc values if *name* is None.
  87. Colormaps added with :func:`register_cmap` take precedence over
  88. built-in colormaps.
  89. Parameters
  90. ----------
  91. name : `matplotlib.colors.Colormap` or str or None, default: None
  92. If a `Colormap` instance, it will be returned. Otherwise, the name of
  93. a colormap known to Matplotlib, which will be resampled by *lut*. The
  94. default, None, means :rc:`image.cmap`.
  95. lut : int or None, default: None
  96. If *name* is not already a Colormap instance and *lut* is not None, the
  97. colormap will be resampled to have *lut* entries in the lookup table.
  98. """
  99. if name is None:
  100. name = mpl.rcParams['image.cmap']
  101. if isinstance(name, colors.Colormap):
  102. return name
  103. cbook._check_in_list(sorted(cmap_d), name=name)
  104. if lut is None:
  105. return cmap_d[name]
  106. else:
  107. return cmap_d[name]._resample(lut)
  108. class ScalarMappable:
  109. """
  110. This is a mixin class to support scalar data to RGBA mapping.
  111. The ScalarMappable makes use of data normalization before returning
  112. RGBA colors from the given colormap.
  113. """
  114. def __init__(self, norm=None, cmap=None):
  115. """
  116. Parameters
  117. ----------
  118. norm : :class:`matplotlib.colors.Normalize` instance
  119. The normalizing object which scales data, typically into the
  120. interval ``[0, 1]``.
  121. If *None*, *norm* defaults to a *colors.Normalize* object which
  122. initializes its scaling based on the first data processed.
  123. cmap : str or :class:`~matplotlib.colors.Colormap` instance
  124. The colormap used to map normalized data values to RGBA colors.
  125. """
  126. self.callbacksSM = cbook.CallbackRegistry()
  127. if cmap is None:
  128. cmap = get_cmap()
  129. if norm is None:
  130. norm = colors.Normalize()
  131. self._A = None
  132. #: The Normalization instance of this ScalarMappable.
  133. self.norm = norm
  134. #: The Colormap instance of this ScalarMappable.
  135. self.cmap = get_cmap(cmap)
  136. #: The last colorbar associated with this ScalarMappable. May be None.
  137. self.colorbar = None
  138. self.update_dict = {'array': False}
  139. def to_rgba(self, x, alpha=None, bytes=False, norm=True):
  140. """
  141. Return a normalized rgba array corresponding to *x*.
  142. In the normal case, *x* is a 1-D or 2-D sequence of scalars, and
  143. the corresponding ndarray of rgba values will be returned,
  144. based on the norm and colormap set for this ScalarMappable.
  145. There is one special case, for handling images that are already
  146. rgb or rgba, such as might have been read from an image file.
  147. If *x* is an ndarray with 3 dimensions,
  148. and the last dimension is either 3 or 4, then it will be
  149. treated as an rgb or rgba array, and no mapping will be done.
  150. The array can be uint8, or it can be floating point with
  151. values in the 0-1 range; otherwise a ValueError will be raised.
  152. If it is a masked array, the mask will be ignored.
  153. If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
  154. will be used to fill in the transparency. If the last dimension
  155. is 4, the *alpha* kwarg is ignored; it does not
  156. replace the pre-existing alpha. A ValueError will be raised
  157. if the third dimension is other than 3 or 4.
  158. In either case, if *bytes* is *False* (default), the rgba
  159. array will be floats in the 0-1 range; if it is *True*,
  160. the returned rgba array will be uint8 in the 0 to 255 range.
  161. If norm is False, no normalization of the input data is
  162. performed, and it is assumed to be in the range (0-1).
  163. """
  164. # First check for special case, image input:
  165. try:
  166. if x.ndim == 3:
  167. if x.shape[2] == 3:
  168. if alpha is None:
  169. alpha = 1
  170. if x.dtype == np.uint8:
  171. alpha = np.uint8(alpha * 255)
  172. m, n = x.shape[:2]
  173. xx = np.empty(shape=(m, n, 4), dtype=x.dtype)
  174. xx[:, :, :3] = x
  175. xx[:, :, 3] = alpha
  176. elif x.shape[2] == 4:
  177. xx = x
  178. else:
  179. raise ValueError("third dimension must be 3 or 4")
  180. if xx.dtype.kind == 'f':
  181. if norm and (xx.max() > 1 or xx.min() < 0):
  182. raise ValueError("Floating point image RGB values "
  183. "must be in the 0..1 range.")
  184. if bytes:
  185. xx = (xx * 255).astype(np.uint8)
  186. elif xx.dtype == np.uint8:
  187. if not bytes:
  188. xx = xx.astype(np.float32) / 255
  189. else:
  190. raise ValueError("Image RGB array must be uint8 or "
  191. "floating point; found %s" % xx.dtype)
  192. return xx
  193. except AttributeError:
  194. # e.g., x is not an ndarray; so try mapping it
  195. pass
  196. # This is the normal case, mapping a scalar array:
  197. x = ma.asarray(x)
  198. if norm:
  199. x = self.norm(x)
  200. rgba = self.cmap(x, alpha=alpha, bytes=bytes)
  201. return rgba
  202. def set_array(self, A):
  203. """Set the image array from numpy array *A*.
  204. Parameters
  205. ----------
  206. A : ndarray
  207. """
  208. self._A = A
  209. self.update_dict['array'] = True
  210. def get_array(self):
  211. 'Return the array'
  212. return self._A
  213. def get_cmap(self):
  214. 'return the colormap'
  215. return self.cmap
  216. def get_clim(self):
  217. 'return the min, max of the color limits for image scaling'
  218. return self.norm.vmin, self.norm.vmax
  219. def set_clim(self, vmin=None, vmax=None):
  220. """
  221. Set the norm limits for image scaling.
  222. Parameters
  223. ----------
  224. vmin, vmax : float
  225. The limits.
  226. The limits may also be passed as a tuple (*vmin*, *vmax*) as a
  227. single positional argument.
  228. .. ACCEPTS: (vmin: float, vmax: float)
  229. """
  230. if vmax is None:
  231. try:
  232. vmin, vmax = vmin
  233. except (TypeError, ValueError):
  234. pass
  235. if vmin is not None:
  236. self.norm.vmin = colors._sanitize_extrema(vmin)
  237. if vmax is not None:
  238. self.norm.vmax = colors._sanitize_extrema(vmax)
  239. self.changed()
  240. def get_alpha(self):
  241. """
  242. Returns
  243. -------
  244. alpha : float
  245. Always returns 1.
  246. """
  247. # This method is intended to be overridden by Artist sub-classes
  248. return 1.
  249. def set_cmap(self, cmap):
  250. """
  251. set the colormap for luminance data
  252. Parameters
  253. ----------
  254. cmap : colormap or registered colormap name
  255. """
  256. cmap = get_cmap(cmap)
  257. self.cmap = cmap
  258. self.changed()
  259. def set_norm(self, norm):
  260. """Set the normalization instance.
  261. Parameters
  262. ----------
  263. norm : `.Normalize`
  264. Notes
  265. -----
  266. If there are any colorbars using the mappable for this norm, setting
  267. the norm of the mappable will reset the norm, locator, and formatters
  268. on the colorbar to default.
  269. """
  270. cbook._check_isinstance((colors.Normalize, None), norm=norm)
  271. if norm is None:
  272. norm = colors.Normalize()
  273. self.norm = norm
  274. self.changed()
  275. def autoscale(self):
  276. """
  277. Autoscale the scalar limits on the norm instance using the
  278. current array
  279. """
  280. if self._A is None:
  281. raise TypeError('You must first set_array for mappable')
  282. self.norm.autoscale(self._A)
  283. self.changed()
  284. def autoscale_None(self):
  285. """
  286. Autoscale the scalar limits on the norm instance using the
  287. current array, changing only limits that are None
  288. """
  289. if self._A is None:
  290. raise TypeError('You must first set_array for mappable')
  291. self.norm.autoscale_None(self._A)
  292. self.changed()
  293. def add_checker(self, checker):
  294. """
  295. Add an entry to a dictionary of boolean flags
  296. that are set to True when the mappable is changed.
  297. """
  298. self.update_dict[checker] = False
  299. def check_update(self, checker):
  300. """
  301. If mappable has changed since the last check,
  302. return True; else return False
  303. """
  304. if self.update_dict[checker]:
  305. self.update_dict[checker] = False
  306. return True
  307. return False
  308. def changed(self):
  309. """
  310. Call this whenever the mappable is changed to notify all the
  311. callbackSM listeners to the 'changed' signal
  312. """
  313. self.callbacksSM.process('changed', self)
  314. for key in self.update_dict:
  315. self.update_dict[key] = True
  316. self.stale = True