cmap_discretisation

pyhelpers.ops.cmap_discretisation(cmap, n_colours)[source]

Create a discrete colour ramp.

See also [OPS-CD-1].

Parameters:
  • cmap (matplotlib.colors.ListedColormap | matplotlib.colors.LinearSegmentedColormap | str) – A colormap instance, e.g. built-in colormaps available via matplotlib.colormaps.get_cmap.

  • n_colours (int) – Number of colours to discretise the colormap.

Returns:

A discrete colormap derived from the continuous cmap.

Return type:

matplotlib.colors.LinearSegmentedColormap

Examples:

>>> from pyhelpers.ops import cmap_discretisation
>>> from pyhelpers.settings import mpl_preferences
>>> mpl_preferences(backend='TkAgg')
>>> import matplotlib
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> cm_accent = cmap_discretisation(cmap=matplotlib.colormaps['Accent'], n_colours=5)
>>> cm_accent.name
'Accent_5'
>>> cm_accent = cmap_discretisation(cmap='Accent', n_colours=5)
>>> cm_accent.name
'Accent_5'
>>> fig = plt.figure(figsize=(10, 2), constrained_layout=True)
>>> ax = fig.add_subplot()
>>> ax.imshow(np.resize(range(100), (5, 100)), cmap=cm_accent, interpolation='nearest')
>>> ax.axis('off')
>>> fig.show()
>>> # from pyhelpers.store import save_figure
>>> # path_to_fig_ = "docs/source/_images/ops-cmap_discretisation-demo"
>>> # save_figure(fig, f"{path_to_fig_}.svg", verbose=True)
>>> # save_figure(fig, f"{path_to_fig_}.pdf", verbose=True)

The exmaple is illustrated in Figure 8:

../_images/ops-cmap_discretisation-demo.svg

Figure 8 An example of discrete colour ramp, created by the function cmap_discretisation().