cm.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. from collections.abc import MutableMapping
  13. import functools
  14. import numpy as np
  15. from numpy import ma
  16. import matplotlib as mpl
  17. import matplotlib.colors as colors
  18. import matplotlib.cbook as cbook
  19. from matplotlib._cm import datad
  20. from matplotlib._cm_listed import cmaps as cmaps_listed
  21. def _reverser(f, x): # Deprecated, remove this at the same time as revcmap.
  22. return f(1 - x) # Toplevel helper for revcmap ensuring cmap picklability.
  23. @cbook.deprecated("3.2", alternative="Colormap.reversed()")
  24. def revcmap(data):
  25. """Can only handle specification *data* in dictionary format."""
  26. data_r = {}
  27. for key, val in data.items():
  28. if callable(val):
  29. # Return a partial object so that the result is picklable.
  30. valnew = functools.partial(_reverser, val)
  31. else:
  32. # Flip x and exchange the y values facing x = 0 and x = 1.
  33. valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)]
  34. data_r[key] = valnew
  35. return data_r
  36. LUTSIZE = mpl.rcParams['image.lut']
  37. def _gen_cmap_registry():
  38. """
  39. Generate a dict mapping standard colormap names to standard colormaps, as
  40. well as the reversed colormaps.
  41. """
  42. cmap_d = {**cmaps_listed}
  43. for name, spec in datad.items():
  44. cmap_d[name] = ( # Precache the cmaps at a fixed lutsize..
  45. colors.LinearSegmentedColormap(name, spec, LUTSIZE)
  46. if 'red' in spec else
  47. colors.ListedColormap(spec['listed'], name)
  48. if 'listed' in spec else
  49. colors.LinearSegmentedColormap.from_list(name, spec, LUTSIZE))
  50. # Generate reversed cmaps.
  51. for cmap in list(cmap_d.values()):
  52. rmap = cmap.reversed()
  53. cmap._global = True
  54. rmap._global = True
  55. cmap_d[rmap.name] = rmap
  56. return cmap_d
  57. class _DeprecatedCmapDictWrapper(MutableMapping):
  58. """Dictionary mapping for deprecated _cmap_d access."""
  59. def __init__(self, cmap_registry):
  60. self._cmap_registry = cmap_registry
  61. def __delitem__(self, key):
  62. self._warn_deprecated()
  63. self._cmap_registry.__delitem__(key)
  64. def __getitem__(self, key):
  65. self._warn_deprecated()
  66. return self._cmap_registry.__getitem__(key)
  67. def __iter__(self):
  68. self._warn_deprecated()
  69. return self._cmap_registry.__iter__()
  70. def __len__(self):
  71. self._warn_deprecated()
  72. return self._cmap_registry.__len__()
  73. def __setitem__(self, key, val):
  74. self._warn_deprecated()
  75. self._cmap_registry.__setitem__(key, val)
  76. def get(self, key, default=None):
  77. self._warn_deprecated()
  78. return self._cmap_registry.get(key, default)
  79. def _warn_deprecated(self):
  80. cbook.warn_deprecated(
  81. "3.3",
  82. message="The global colormaps dictionary is no longer "
  83. "considered public API.",
  84. alternative="Please use register_cmap() and get_cmap() to "
  85. "access the contents of the dictionary."
  86. )
  87. _cmap_registry = _gen_cmap_registry()
  88. locals().update(_cmap_registry)
  89. # This is no longer considered public API
  90. cmap_d = _DeprecatedCmapDictWrapper(_cmap_registry)
  91. # Continue with definitions ...
  92. def register_cmap(name=None, cmap=None, data=None, lut=None):
  93. """
  94. Add a colormap to the set recognized by :func:`get_cmap`.
  95. It can be used in two ways::
  96. register_cmap(name='swirly', cmap=swirly_cmap)
  97. register_cmap(name='choppy', data=choppydata, lut=128)
  98. In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`
  99. instance. The *name* is optional; if absent, the name will
  100. be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.
  101. The second case is deprecated. Here, the three arguments are passed to
  102. the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,
  103. and the resulting colormap is registered. Instead of this implicit
  104. colormap creation, create a `.LinearSegmentedColormap` and use the first
  105. case: ``register_cmap(cmap=LinearSegmentedColormap(name, data, lut))``.
  106. Notes
  107. -----
  108. Registering a colormap stores a reference to the colormap object
  109. which can currently be modified and inadvertantly change the global
  110. colormap state. This behavior is deprecated and in Matplotlib 3.5
  111. the registered colormap will be immutable.
  112. """
  113. cbook._check_isinstance((str, None), name=name)
  114. if name is None:
  115. try:
  116. name = cmap.name
  117. except AttributeError as err:
  118. raise ValueError("Arguments must include a name or a "
  119. "Colormap") from err
  120. if isinstance(cmap, colors.Colormap):
  121. cmap._global = True
  122. _cmap_registry[name] = cmap
  123. return
  124. if lut is not None or data is not None:
  125. cbook.warn_deprecated(
  126. "3.3",
  127. message="Passing raw data via parameters data and lut to "
  128. "register_cmap() is deprecated since %(since)s and will "
  129. "become an error %(removal)s. Instead use: register_cmap("
  130. "cmap=LinearSegmentedColormap(name, data, lut))")
  131. # For the remainder, let exceptions propagate.
  132. if lut is None:
  133. lut = mpl.rcParams['image.lut']
  134. cmap = colors.LinearSegmentedColormap(name, data, lut)
  135. cmap._global = True
  136. _cmap_registry[name] = cmap
  137. def get_cmap(name=None, lut=None):
  138. """
  139. Get a colormap instance, defaulting to rc values if *name* is None.
  140. Colormaps added with :func:`register_cmap` take precedence over
  141. built-in colormaps.
  142. Notes
  143. -----
  144. Currently, this returns the global colormap object, which is deprecated.
  145. In Matplotlib 3.5, you will no longer be able to modify the global
  146. colormaps in-place.
  147. Parameters
  148. ----------
  149. name : `matplotlib.colors.Colormap` or str or None, default: None
  150. If a `.Colormap` instance, it will be returned. Otherwise, the name of
  151. a colormap known to Matplotlib, which will be resampled by *lut*. The
  152. default, None, means :rc:`image.cmap`.
  153. lut : int or None, default: None
  154. If *name* is not already a Colormap instance and *lut* is not None, the
  155. colormap will be resampled to have *lut* entries in the lookup table.
  156. """
  157. if name is None:
  158. name = mpl.rcParams['image.cmap']
  159. if isinstance(name, colors.Colormap):
  160. return name
  161. cbook._check_in_list(sorted(_cmap_registry), name=name)
  162. if lut is None:
  163. return _cmap_registry[name]
  164. else:
  165. return _cmap_registry[name]._resample(lut)
  166. class ScalarMappable:
  167. """
  168. A mixin class to map scalar data to RGBA.
  169. The ScalarMappable applies data normalization before returning RGBA colors
  170. from the given colormap.
  171. """
  172. def __init__(self, norm=None, cmap=None):
  173. """
  174. Parameters
  175. ----------
  176. norm : `matplotlib.colors.Normalize` (or subclass thereof)
  177. The normalizing object which scales data, typically into the
  178. interval ``[0, 1]``.
  179. If *None*, *norm* defaults to a *colors.Normalize* object which
  180. initializes its scaling based on the first data processed.
  181. cmap : str or `~matplotlib.colors.Colormap`
  182. The colormap used to map normalized data values to RGBA colors.
  183. """
  184. self._A = None
  185. self.norm = None # So that the setter knows we're initializing.
  186. self.set_norm(norm) # The Normalize instance of this ScalarMappable.
  187. self.cmap = None # So that the setter knows we're initializing.
  188. self.set_cmap(cmap) # The Colormap instance of this ScalarMappable.
  189. #: The last colorbar associated with this ScalarMappable. May be None.
  190. self.colorbar = None
  191. self.callbacksSM = cbook.CallbackRegistry()
  192. self._update_dict = {'array': False}
  193. def _scale_norm(self, norm, vmin, vmax):
  194. """
  195. Helper for initial scaling.
  196. Used by public functions that create a ScalarMappable and support
  197. parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm*
  198. will take precedence over *vmin*, *vmax*.
  199. Note that this method does not set the norm.
  200. """
  201. if vmin is not None or vmax is not None:
  202. self.set_clim(vmin, vmax)
  203. if norm is not None:
  204. cbook.warn_deprecated(
  205. "3.3",
  206. message="Passing parameters norm and vmin/vmax "
  207. "simultaneously is deprecated since %(since)s and "
  208. "will become an error %(removal)s. Please pass "
  209. "vmin/vmax directly to the norm when creating it.")
  210. # always resolve the autoscaling so we have concrete limits
  211. # rather than deferring to draw time.
  212. self.autoscale_None()
  213. def to_rgba(self, x, alpha=None, bytes=False, norm=True):
  214. """
  215. Return a normalized rgba array corresponding to *x*.
  216. In the normal case, *x* is a 1-D or 2-D sequence of scalars, and
  217. the corresponding ndarray of rgba values will be returned,
  218. based on the norm and colormap set for this ScalarMappable.
  219. There is one special case, for handling images that are already
  220. rgb or rgba, such as might have been read from an image file.
  221. If *x* is an ndarray with 3 dimensions,
  222. and the last dimension is either 3 or 4, then it will be
  223. treated as an rgb or rgba array, and no mapping will be done.
  224. The array can be uint8, or it can be floating point with
  225. values in the 0-1 range; otherwise a ValueError will be raised.
  226. If it is a masked array, the mask will be ignored.
  227. If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
  228. will be used to fill in the transparency. If the last dimension
  229. is 4, the *alpha* kwarg is ignored; it does not
  230. replace the pre-existing alpha. A ValueError will be raised
  231. if the third dimension is other than 3 or 4.
  232. In either case, if *bytes* is *False* (default), the rgba
  233. array will be floats in the 0-1 range; if it is *True*,
  234. the returned rgba array will be uint8 in the 0 to 255 range.
  235. If norm is False, no normalization of the input data is
  236. performed, and it is assumed to be in the range (0-1).
  237. """
  238. # First check for special case, image input:
  239. try:
  240. if x.ndim == 3:
  241. if x.shape[2] == 3:
  242. if alpha is None:
  243. alpha = 1
  244. if x.dtype == np.uint8:
  245. alpha = np.uint8(alpha * 255)
  246. m, n = x.shape[:2]
  247. xx = np.empty(shape=(m, n, 4), dtype=x.dtype)
  248. xx[:, :, :3] = x
  249. xx[:, :, 3] = alpha
  250. elif x.shape[2] == 4:
  251. xx = x
  252. else:
  253. raise ValueError("Third dimension must be 3 or 4")
  254. if xx.dtype.kind == 'f':
  255. if norm and (xx.max() > 1 or xx.min() < 0):
  256. raise ValueError("Floating point image RGB values "
  257. "must be in the 0..1 range.")
  258. if bytes:
  259. xx = (xx * 255).astype(np.uint8)
  260. elif xx.dtype == np.uint8:
  261. if not bytes:
  262. xx = xx.astype(np.float32) / 255
  263. else:
  264. raise ValueError("Image RGB array must be uint8 or "
  265. "floating point; found %s" % xx.dtype)
  266. return xx
  267. except AttributeError:
  268. # e.g., x is not an ndarray; so try mapping it
  269. pass
  270. # This is the normal case, mapping a scalar array:
  271. x = ma.asarray(x)
  272. if norm:
  273. x = self.norm(x)
  274. rgba = self.cmap(x, alpha=alpha, bytes=bytes)
  275. return rgba
  276. def set_array(self, A):
  277. """
  278. Set the image array from numpy array *A*.
  279. Parameters
  280. ----------
  281. A : ndarray
  282. """
  283. self._A = A
  284. self._update_dict['array'] = True
  285. def get_array(self):
  286. """Return the data array."""
  287. return self._A
  288. def get_cmap(self):
  289. """Return the `.Colormap` instance."""
  290. return self.cmap
  291. def get_clim(self):
  292. """
  293. Return the values (min, max) that are mapped to the colormap limits.
  294. """
  295. return self.norm.vmin, self.norm.vmax
  296. def set_clim(self, vmin=None, vmax=None):
  297. """
  298. Set the norm limits for image scaling.
  299. Parameters
  300. ----------
  301. vmin, vmax : float
  302. The limits.
  303. The limits may also be passed as a tuple (*vmin*, *vmax*) as a
  304. single positional argument.
  305. .. ACCEPTS: (vmin: float, vmax: float)
  306. """
  307. if vmax is None:
  308. try:
  309. vmin, vmax = vmin
  310. except (TypeError, ValueError):
  311. pass
  312. if vmin is not None:
  313. self.norm.vmin = colors._sanitize_extrema(vmin)
  314. if vmax is not None:
  315. self.norm.vmax = colors._sanitize_extrema(vmax)
  316. self.changed()
  317. def get_alpha(self):
  318. """
  319. Returns
  320. -------
  321. float
  322. Always returns 1.
  323. """
  324. # This method is intended to be overridden by Artist sub-classes
  325. return 1.
  326. def set_cmap(self, cmap):
  327. """
  328. Set the colormap for luminance data.
  329. Parameters
  330. ----------
  331. cmap : `.Colormap` or str or None
  332. """
  333. in_init = self.cmap is None
  334. cmap = get_cmap(cmap)
  335. self.cmap = cmap
  336. if not in_init:
  337. self.changed() # Things are not set up properly yet.
  338. def set_norm(self, norm):
  339. """
  340. Set the normalization instance.
  341. Parameters
  342. ----------
  343. norm : `.Normalize` or None
  344. Notes
  345. -----
  346. If there are any colorbars using the mappable for this norm, setting
  347. the norm of the mappable will reset the norm, locator, and formatters
  348. on the colorbar to default.
  349. """
  350. cbook._check_isinstance((colors.Normalize, None), norm=norm)
  351. in_init = self.norm is None
  352. if norm is None:
  353. norm = colors.Normalize()
  354. self.norm = norm
  355. if not in_init:
  356. self.changed() # Things are not set up properly yet.
  357. def autoscale(self):
  358. """
  359. Autoscale the scalar limits on the norm instance using the
  360. current array
  361. """
  362. if self._A is None:
  363. raise TypeError('You must first set_array for mappable')
  364. self.norm.autoscale(self._A)
  365. self.changed()
  366. def autoscale_None(self):
  367. """
  368. Autoscale the scalar limits on the norm instance using the
  369. current array, changing only limits that are None
  370. """
  371. if self._A is None:
  372. raise TypeError('You must first set_array for mappable')
  373. self.norm.autoscale_None(self._A)
  374. self.changed()
  375. def _add_checker(self, checker):
  376. """
  377. Add an entry to a dictionary of boolean flags
  378. that are set to True when the mappable is changed.
  379. """
  380. self._update_dict[checker] = False
  381. def _check_update(self, checker):
  382. """Return whether mappable has changed since the last check."""
  383. if self._update_dict[checker]:
  384. self._update_dict[checker] = False
  385. return True
  386. return False
  387. def changed(self):
  388. """
  389. Call this whenever the mappable is changed to notify all the
  390. callbackSM listeners to the 'changed' signal.
  391. """
  392. self.callbacksSM.process('changed', self)
  393. for key in self._update_dict:
  394. self._update_dict[key] = True
  395. self.stale = True
  396. update_dict = cbook._deprecate_privatize_attribute("3.3")
  397. @cbook.deprecated("3.3")
  398. def add_checker(self, checker):
  399. return self._add_checker(checker)
  400. @cbook.deprecated("3.3")
  401. def check_update(self, checker):
  402. return self._check_update(checker)