cm.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. :ref:`colormap-manipulation` for examples of how to make
  6. colormaps.
  7. :ref:`colormaps` an in-depth discussion of choosing
  8. colormaps.
  9. :ref:`colormapnorms` for more details about data normalization.
  10. """
  11. from collections.abc import Mapping
  12. import functools
  13. import numpy as np
  14. from numpy import ma
  15. import matplotlib as mpl
  16. from matplotlib import _api, colors, cbook, scale
  17. from matplotlib._cm import datad
  18. from matplotlib._cm_listed import cmaps as cmaps_listed
  19. _LUTSIZE = mpl.rcParams['image.lut']
  20. def _gen_cmap_registry():
  21. """
  22. Generate a dict mapping standard colormap names to standard colormaps, as
  23. well as the reversed colormaps.
  24. """
  25. cmap_d = {**cmaps_listed}
  26. for name, spec in datad.items():
  27. cmap_d[name] = ( # Precache the cmaps at a fixed lutsize..
  28. colors.LinearSegmentedColormap(name, spec, _LUTSIZE)
  29. if 'red' in spec else
  30. colors.ListedColormap(spec['listed'], name)
  31. if 'listed' in spec else
  32. colors.LinearSegmentedColormap.from_list(name, spec, _LUTSIZE))
  33. # Register colormap aliases for gray and grey.
  34. cmap_d['grey'] = cmap_d['gray']
  35. cmap_d['gist_grey'] = cmap_d['gist_gray']
  36. cmap_d['gist_yerg'] = cmap_d['gist_yarg']
  37. cmap_d['Grays'] = cmap_d['Greys']
  38. # Generate reversed cmaps.
  39. for cmap in list(cmap_d.values()):
  40. rmap = cmap.reversed()
  41. cmap_d[rmap.name] = rmap
  42. return cmap_d
  43. class ColormapRegistry(Mapping):
  44. r"""
  45. Container for colormaps that are known to Matplotlib by name.
  46. The universal registry instance is `matplotlib.colormaps`. There should be
  47. no need for users to instantiate `.ColormapRegistry` themselves.
  48. Read access uses a dict-like interface mapping names to `.Colormap`\s::
  49. import matplotlib as mpl
  50. cmap = mpl.colormaps['viridis']
  51. Returned `.Colormap`\s are copies, so that their modification does not
  52. change the global definition of the colormap.
  53. Additional colormaps can be added via `.ColormapRegistry.register`::
  54. mpl.colormaps.register(my_colormap)
  55. To get a list of all registered colormaps, you can do::
  56. from matplotlib import colormaps
  57. list(colormaps)
  58. """
  59. def __init__(self, cmaps):
  60. self._cmaps = cmaps
  61. self._builtin_cmaps = tuple(cmaps)
  62. # A shim to allow register_cmap() to force an override
  63. self._allow_override_builtin = False
  64. def __getitem__(self, item):
  65. try:
  66. return self._cmaps[item].copy()
  67. except KeyError:
  68. raise KeyError(f"{item!r} is not a known colormap name") from None
  69. def __iter__(self):
  70. return iter(self._cmaps)
  71. def __len__(self):
  72. return len(self._cmaps)
  73. def __str__(self):
  74. return ('ColormapRegistry; available colormaps:\n' +
  75. ', '.join(f"'{name}'" for name in self))
  76. def __call__(self):
  77. """
  78. Return a list of the registered colormap names.
  79. This exists only for backward-compatibility in `.pyplot` which had a
  80. ``plt.colormaps()`` method. The recommended way to get this list is
  81. now ``list(colormaps)``.
  82. """
  83. return list(self)
  84. def register(self, cmap, *, name=None, force=False):
  85. """
  86. Register a new colormap.
  87. The colormap name can then be used as a string argument to any ``cmap``
  88. parameter in Matplotlib. It is also available in ``pyplot.get_cmap``.
  89. The colormap registry stores a copy of the given colormap, so that
  90. future changes to the original colormap instance do not affect the
  91. registered colormap. Think of this as the registry taking a snapshot
  92. of the colormap at registration.
  93. Parameters
  94. ----------
  95. cmap : matplotlib.colors.Colormap
  96. The colormap to register.
  97. name : str, optional
  98. The name for the colormap. If not given, ``cmap.name`` is used.
  99. force : bool, default: False
  100. If False, a ValueError is raised if trying to overwrite an already
  101. registered name. True supports overwriting registered colormaps
  102. other than the builtin colormaps.
  103. """
  104. _api.check_isinstance(colors.Colormap, cmap=cmap)
  105. name = name or cmap.name
  106. if name in self:
  107. if not force:
  108. # don't allow registering an already existing cmap
  109. # unless explicitly asked to
  110. raise ValueError(
  111. f'A colormap named "{name}" is already registered.')
  112. elif (name in self._builtin_cmaps
  113. and not self._allow_override_builtin):
  114. # We don't allow overriding a builtin unless privately
  115. # coming from register_cmap()
  116. raise ValueError("Re-registering the builtin cmap "
  117. f"{name!r} is not allowed.")
  118. # Warn that we are updating an already existing colormap
  119. _api.warn_external(f"Overwriting the cmap {name!r} "
  120. "that was already in the registry.")
  121. self._cmaps[name] = cmap.copy()
  122. # Someone may set the extremes of a builtin colormap and want to register it
  123. # with a different name for future lookups. The object would still have the
  124. # builtin name, so we should update it to the registered name
  125. if self._cmaps[name].name != name:
  126. self._cmaps[name].name = name
  127. def unregister(self, name):
  128. """
  129. Remove a colormap from the registry.
  130. You cannot remove built-in colormaps.
  131. If the named colormap is not registered, returns with no error, raises
  132. if you try to de-register a default colormap.
  133. .. warning::
  134. Colormap names are currently a shared namespace that may be used
  135. by multiple packages. Use `unregister` only if you know you
  136. have registered that name before. In particular, do not
  137. unregister just in case to clean the name before registering a
  138. new colormap.
  139. Parameters
  140. ----------
  141. name : str
  142. The name of the colormap to be removed.
  143. Raises
  144. ------
  145. ValueError
  146. If you try to remove a default built-in colormap.
  147. """
  148. if name in self._builtin_cmaps:
  149. raise ValueError(f"cannot unregister {name!r} which is a builtin "
  150. "colormap.")
  151. self._cmaps.pop(name, None)
  152. def get_cmap(self, cmap):
  153. """
  154. Return a color map specified through *cmap*.
  155. Parameters
  156. ----------
  157. cmap : str or `~matplotlib.colors.Colormap` or None
  158. - if a `.Colormap`, return it
  159. - if a string, look it up in ``mpl.colormaps``
  160. - if None, return the Colormap defined in :rc:`image.cmap`
  161. Returns
  162. -------
  163. Colormap
  164. """
  165. # get the default color map
  166. if cmap is None:
  167. return self[mpl.rcParams["image.cmap"]]
  168. # if the user passed in a Colormap, simply return it
  169. if isinstance(cmap, colors.Colormap):
  170. return cmap
  171. if isinstance(cmap, str):
  172. _api.check_in_list(sorted(_colormaps), cmap=cmap)
  173. # otherwise, it must be a string so look it up
  174. return self[cmap]
  175. raise TypeError(
  176. 'get_cmap expects None or an instance of a str or Colormap . ' +
  177. f'you passed {cmap!r} of type {type(cmap)}'
  178. )
  179. # public access to the colormaps should be via `matplotlib.colormaps`. For now,
  180. # we still create the registry here, but that should stay an implementation
  181. # detail.
  182. _colormaps = ColormapRegistry(_gen_cmap_registry())
  183. globals().update(_colormaps)
  184. @_api.deprecated("3.7", alternative="``matplotlib.colormaps.register(name)``")
  185. def register_cmap(name=None, cmap=None, *, override_builtin=False):
  186. """
  187. Add a colormap to the set recognized by :func:`get_cmap`.
  188. Register a new colormap to be accessed by name ::
  189. LinearSegmentedColormap('swirly', data, lut)
  190. register_cmap(cmap=swirly_cmap)
  191. Parameters
  192. ----------
  193. name : str, optional
  194. The name that can be used in :func:`get_cmap` or :rc:`image.cmap`
  195. If absent, the name will be the :attr:`~matplotlib.colors.Colormap.name`
  196. attribute of the *cmap*.
  197. cmap : matplotlib.colors.Colormap
  198. Despite being the second argument and having a default value, this
  199. is a required argument.
  200. override_builtin : bool
  201. Allow built-in colormaps to be overridden by a user-supplied
  202. colormap.
  203. Please do not use this unless you are sure you need it.
  204. """
  205. _api.check_isinstance((str, None), name=name)
  206. if name is None:
  207. try:
  208. name = cmap.name
  209. except AttributeError as err:
  210. raise ValueError("Arguments must include a name or a "
  211. "Colormap") from err
  212. # override_builtin is allowed here for backward compatibility
  213. # this is just a shim to enable that to work privately in
  214. # the global ColormapRegistry
  215. _colormaps._allow_override_builtin = override_builtin
  216. _colormaps.register(cmap, name=name, force=override_builtin)
  217. _colormaps._allow_override_builtin = False
  218. def _get_cmap(name=None, lut=None):
  219. """
  220. Get a colormap instance, defaulting to rc values if *name* is None.
  221. Parameters
  222. ----------
  223. name : `~matplotlib.colors.Colormap` or str or None, default: None
  224. If a `.Colormap` instance, it will be returned. Otherwise, the name of
  225. a colormap known to Matplotlib, which will be resampled by *lut*. The
  226. default, None, means :rc:`image.cmap`.
  227. lut : int or None, default: None
  228. If *name* is not already a Colormap instance and *lut* is not None, the
  229. colormap will be resampled to have *lut* entries in the lookup table.
  230. Returns
  231. -------
  232. Colormap
  233. """
  234. if name is None:
  235. name = mpl.rcParams['image.cmap']
  236. if isinstance(name, colors.Colormap):
  237. return name
  238. _api.check_in_list(sorted(_colormaps), name=name)
  239. if lut is None:
  240. return _colormaps[name]
  241. else:
  242. return _colormaps[name].resampled(lut)
  243. # do it in two steps like this so we can have an un-deprecated version in
  244. # pyplot.
  245. get_cmap = _api.deprecated(
  246. '3.7',
  247. name='get_cmap',
  248. alternative=(
  249. "``matplotlib.colormaps[name]`` " +
  250. "or ``matplotlib.colormaps.get_cmap(obj)``"
  251. )
  252. )(_get_cmap)
  253. @_api.deprecated("3.7",
  254. alternative="``matplotlib.colormaps.unregister(name)``")
  255. def unregister_cmap(name):
  256. """
  257. Remove a colormap recognized by :func:`get_cmap`.
  258. You may not remove built-in colormaps.
  259. If the named colormap is not registered, returns with no error, raises
  260. if you try to de-register a default colormap.
  261. .. warning::
  262. Colormap names are currently a shared namespace that may be used
  263. by multiple packages. Use `unregister_cmap` only if you know you
  264. have registered that name before. In particular, do not
  265. unregister just in case to clean the name before registering a
  266. new colormap.
  267. Parameters
  268. ----------
  269. name : str
  270. The name of the colormap to be un-registered
  271. Returns
  272. -------
  273. ColorMap or None
  274. If the colormap was registered, return it if not return `None`
  275. Raises
  276. ------
  277. ValueError
  278. If you try to de-register a default built-in colormap.
  279. """
  280. cmap = _colormaps.get(name, None)
  281. _colormaps.unregister(name)
  282. return cmap
  283. def _auto_norm_from_scale(scale_cls):
  284. """
  285. Automatically generate a norm class from *scale_cls*.
  286. This differs from `.colors.make_norm_from_scale` in the following points:
  287. - This function is not a class decorator, but directly returns a norm class
  288. (as if decorating `.Normalize`).
  289. - The scale is automatically constructed with ``nonpositive="mask"``, if it
  290. supports such a parameter, to work around the difference in defaults
  291. between standard scales (which use "clip") and norms (which use "mask").
  292. Note that ``make_norm_from_scale`` caches the generated norm classes
  293. (not the instances) and reuses them for later calls. For example,
  294. ``type(_auto_norm_from_scale("log")) == LogNorm``.
  295. """
  296. # Actually try to construct an instance, to verify whether
  297. # ``nonpositive="mask"`` is supported.
  298. try:
  299. norm = colors.make_norm_from_scale(
  300. functools.partial(scale_cls, nonpositive="mask"))(
  301. colors.Normalize)()
  302. except TypeError:
  303. norm = colors.make_norm_from_scale(scale_cls)(
  304. colors.Normalize)()
  305. return type(norm)
  306. class ScalarMappable:
  307. """
  308. A mixin class to map scalar data to RGBA.
  309. The ScalarMappable applies data normalization before returning RGBA colors
  310. from the given colormap.
  311. """
  312. def __init__(self, norm=None, cmap=None):
  313. """
  314. Parameters
  315. ----------
  316. norm : `.Normalize` (or subclass thereof) or str or None
  317. The normalizing object which scales data, typically into the
  318. interval ``[0, 1]``.
  319. If a `str`, a `.Normalize` subclass is dynamically generated based
  320. on the scale with the corresponding name.
  321. If *None*, *norm* defaults to a *colors.Normalize* object which
  322. initializes its scaling based on the first data processed.
  323. cmap : str or `~matplotlib.colors.Colormap`
  324. The colormap used to map normalized data values to RGBA colors.
  325. """
  326. self._A = None
  327. self._norm = None # So that the setter knows we're initializing.
  328. self.set_norm(norm) # The Normalize instance of this ScalarMappable.
  329. self.cmap = None # So that the setter knows we're initializing.
  330. self.set_cmap(cmap) # The Colormap instance of this ScalarMappable.
  331. #: The last colorbar associated with this ScalarMappable. May be None.
  332. self.colorbar = None
  333. self.callbacks = cbook.CallbackRegistry(signals=["changed"])
  334. def _scale_norm(self, norm, vmin, vmax):
  335. """
  336. Helper for initial scaling.
  337. Used by public functions that create a ScalarMappable and support
  338. parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm*
  339. will take precedence over *vmin*, *vmax*.
  340. Note that this method does not set the norm.
  341. """
  342. if vmin is not None or vmax is not None:
  343. self.set_clim(vmin, vmax)
  344. if isinstance(norm, colors.Normalize):
  345. raise ValueError(
  346. "Passing a Normalize instance simultaneously with "
  347. "vmin/vmax is not supported. Please pass vmin/vmax "
  348. "directly to the norm when creating it.")
  349. # always resolve the autoscaling so we have concrete limits
  350. # rather than deferring to draw time.
  351. self.autoscale_None()
  352. def to_rgba(self, x, alpha=None, bytes=False, norm=True):
  353. """
  354. Return a normalized RGBA array corresponding to *x*.
  355. In the normal case, *x* is a 1D or 2D sequence of scalars, and
  356. the corresponding `~numpy.ndarray` of RGBA values will be returned,
  357. based on the norm and colormap set for this ScalarMappable.
  358. There is one special case, for handling images that are already
  359. RGB or RGBA, such as might have been read from an image file.
  360. If *x* is an `~numpy.ndarray` with 3 dimensions,
  361. and the last dimension is either 3 or 4, then it will be
  362. treated as an RGB or RGBA array, and no mapping will be done.
  363. The array can be `~numpy.uint8`, or it can be floats with
  364. values in the 0-1 range; otherwise a ValueError will be raised.
  365. If it is a masked array, any masked elements will be set to 0 alpha.
  366. If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
  367. will be used to fill in the transparency. If the last dimension
  368. is 4, the *alpha* kwarg is ignored; it does not
  369. replace the preexisting alpha. A ValueError will be raised
  370. if the third dimension is other than 3 or 4.
  371. In either case, if *bytes* is *False* (default), the RGBA
  372. array will be floats in the 0-1 range; if it is *True*,
  373. the returned RGBA array will be `~numpy.uint8` in the 0 to 255 range.
  374. If norm is False, no normalization of the input data is
  375. performed, and it is assumed to be in the range (0-1).
  376. """
  377. # First check for special case, image input:
  378. try:
  379. if x.ndim == 3:
  380. if x.shape[2] == 3:
  381. if alpha is None:
  382. alpha = 1
  383. if x.dtype == np.uint8:
  384. alpha = np.uint8(alpha * 255)
  385. m, n = x.shape[:2]
  386. xx = np.empty(shape=(m, n, 4), dtype=x.dtype)
  387. xx[:, :, :3] = x
  388. xx[:, :, 3] = alpha
  389. elif x.shape[2] == 4:
  390. xx = x
  391. else:
  392. raise ValueError("Third dimension must be 3 or 4")
  393. if xx.dtype.kind == 'f':
  394. if norm and (xx.max() > 1 or xx.min() < 0):
  395. raise ValueError("Floating point image RGB values "
  396. "must be in the 0..1 range.")
  397. if bytes:
  398. xx = (xx * 255).astype(np.uint8)
  399. elif xx.dtype == np.uint8:
  400. if not bytes:
  401. xx = xx.astype(np.float32) / 255
  402. else:
  403. raise ValueError("Image RGB array must be uint8 or "
  404. "floating point; found %s" % xx.dtype)
  405. # Account for any masked entries in the original array
  406. # If any of R, G, B, or A are masked for an entry, we set alpha to 0
  407. if np.ma.is_masked(x):
  408. xx[np.any(np.ma.getmaskarray(x), axis=2), 3] = 0
  409. return xx
  410. except AttributeError:
  411. # e.g., x is not an ndarray; so try mapping it
  412. pass
  413. # This is the normal case, mapping a scalar array:
  414. x = ma.asarray(x)
  415. if norm:
  416. x = self.norm(x)
  417. rgba = self.cmap(x, alpha=alpha, bytes=bytes)
  418. return rgba
  419. def set_array(self, A):
  420. """
  421. Set the value array from array-like *A*.
  422. Parameters
  423. ----------
  424. A : array-like or None
  425. The values that are mapped to colors.
  426. The base class `.ScalarMappable` does not make any assumptions on
  427. the dimensionality and shape of the value array *A*.
  428. """
  429. if A is None:
  430. self._A = None
  431. return
  432. A = cbook.safe_masked_invalid(A, copy=True)
  433. if not np.can_cast(A.dtype, float, "same_kind"):
  434. raise TypeError(f"Image data of dtype {A.dtype} cannot be "
  435. "converted to float")
  436. self._A = A
  437. def get_array(self):
  438. """
  439. Return the array of values, that are mapped to colors.
  440. The base class `.ScalarMappable` does not make any assumptions on
  441. the dimensionality and shape of the array.
  442. """
  443. return self._A
  444. def get_cmap(self):
  445. """Return the `.Colormap` instance."""
  446. return self.cmap
  447. def get_clim(self):
  448. """
  449. Return the values (min, max) that are mapped to the colormap limits.
  450. """
  451. return self.norm.vmin, self.norm.vmax
  452. def set_clim(self, vmin=None, vmax=None):
  453. """
  454. Set the norm limits for image scaling.
  455. Parameters
  456. ----------
  457. vmin, vmax : float
  458. The limits.
  459. The limits may also be passed as a tuple (*vmin*, *vmax*) as a
  460. single positional argument.
  461. .. ACCEPTS: (vmin: float, vmax: float)
  462. """
  463. # If the norm's limits are updated self.changed() will be called
  464. # through the callbacks attached to the norm
  465. if vmax is None:
  466. try:
  467. vmin, vmax = vmin
  468. except (TypeError, ValueError):
  469. pass
  470. if vmin is not None:
  471. self.norm.vmin = colors._sanitize_extrema(vmin)
  472. if vmax is not None:
  473. self.norm.vmax = colors._sanitize_extrema(vmax)
  474. def get_alpha(self):
  475. """
  476. Returns
  477. -------
  478. float
  479. Always returns 1.
  480. """
  481. # This method is intended to be overridden by Artist sub-classes
  482. return 1.
  483. def set_cmap(self, cmap):
  484. """
  485. Set the colormap for luminance data.
  486. Parameters
  487. ----------
  488. cmap : `.Colormap` or str or None
  489. """
  490. in_init = self.cmap is None
  491. self.cmap = _ensure_cmap(cmap)
  492. if not in_init:
  493. self.changed() # Things are not set up properly yet.
  494. @property
  495. def norm(self):
  496. return self._norm
  497. @norm.setter
  498. def norm(self, norm):
  499. _api.check_isinstance((colors.Normalize, str, None), norm=norm)
  500. if norm is None:
  501. norm = colors.Normalize()
  502. elif isinstance(norm, str):
  503. try:
  504. scale_cls = scale._scale_mapping[norm]
  505. except KeyError:
  506. raise ValueError(
  507. "Invalid norm str name; the following values are "
  508. f"supported: {', '.join(scale._scale_mapping)}"
  509. ) from None
  510. norm = _auto_norm_from_scale(scale_cls)()
  511. if norm is self.norm:
  512. # We aren't updating anything
  513. return
  514. in_init = self.norm is None
  515. # Remove the current callback and connect to the new one
  516. if not in_init:
  517. self.norm.callbacks.disconnect(self._id_norm)
  518. self._norm = norm
  519. self._id_norm = self.norm.callbacks.connect('changed',
  520. self.changed)
  521. if not in_init:
  522. self.changed()
  523. def set_norm(self, norm):
  524. """
  525. Set the normalization instance.
  526. Parameters
  527. ----------
  528. norm : `.Normalize` or str or None
  529. Notes
  530. -----
  531. If there are any colorbars using the mappable for this norm, setting
  532. the norm of the mappable will reset the norm, locator, and formatters
  533. on the colorbar to default.
  534. """
  535. self.norm = norm
  536. def autoscale(self):
  537. """
  538. Autoscale the scalar limits on the norm instance using the
  539. current array
  540. """
  541. if self._A is None:
  542. raise TypeError('You must first set_array for mappable')
  543. # If the norm's limits are updated self.changed() will be called
  544. # through the callbacks attached to the norm
  545. self.norm.autoscale(self._A)
  546. def autoscale_None(self):
  547. """
  548. Autoscale the scalar limits on the norm instance using the
  549. current array, changing only limits that are None
  550. """
  551. if self._A is None:
  552. raise TypeError('You must first set_array for mappable')
  553. # If the norm's limits are updated self.changed() will be called
  554. # through the callbacks attached to the norm
  555. self.norm.autoscale_None(self._A)
  556. def changed(self):
  557. """
  558. Call this whenever the mappable is changed to notify all the
  559. callbackSM listeners to the 'changed' signal.
  560. """
  561. self.callbacks.process('changed', self)
  562. self.stale = True
  563. # The docstrings here must be generic enough to apply to all relevant methods.
  564. mpl._docstring.interpd.update(
  565. cmap_doc="""\
  566. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
  567. The Colormap instance or registered colormap name used to map scalar data
  568. to colors.""",
  569. norm_doc="""\
  570. norm : str or `~matplotlib.colors.Normalize`, optional
  571. The normalization method used to scale scalar data to the [0, 1] range
  572. before mapping to colors using *cmap*. By default, a linear scaling is
  573. used, mapping the lowest value to 0 and the highest to 1.
  574. If given, this can be one of the following:
  575. - An instance of `.Normalize` or one of its subclasses
  576. (see :ref:`colormapnorms`).
  577. - A scale name, i.e. one of "linear", "log", "symlog", "logit", etc. For a
  578. list of available scales, call `matplotlib.scale.get_scale_names()`.
  579. In that case, a suitable `.Normalize` subclass is dynamically generated
  580. and instantiated.""",
  581. vmin_vmax_doc="""\
  582. vmin, vmax : float, optional
  583. When using scalar data and no explicit *norm*, *vmin* and *vmax* define
  584. the data range that the colormap covers. By default, the colormap covers
  585. the complete value range of the supplied data. It is an error to use
  586. *vmin*/*vmax* when a *norm* instance is given (but using a `str` *norm*
  587. name together with *vmin*/*vmax* is acceptable).""",
  588. )
  589. def _ensure_cmap(cmap):
  590. """
  591. Ensure that we have a `.Colormap` object.
  592. For internal use to preserve type stability of errors.
  593. Parameters
  594. ----------
  595. cmap : None, str, Colormap
  596. - if a `Colormap`, return it
  597. - if a string, look it up in mpl.colormaps
  598. - if None, look up the default color map in mpl.colormaps
  599. Returns
  600. -------
  601. Colormap
  602. """
  603. if isinstance(cmap, colors.Colormap):
  604. return cmap
  605. cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"]
  606. # use check_in_list to ensure type stability of the exception raised by
  607. # the internal usage of this (ValueError vs KeyError)
  608. if cmap_name not in _colormaps:
  609. _api.check_in_list(sorted(_colormaps), cmap=cmap_name)
  610. return mpl.colormaps[cmap_name]