cmap_discretization

pyhelpers.viz.cmap_discretization(cmap, n_colors)[source]

Creates a discrete colormap based on the input.

Reference: [OPS-CD-1].

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

  • n_colors (int) – Number of colors to discretize the colormap.

Returns:

A discrete colormap derived from the continuous cmap.

Return type:

matplotlib.colors.LinearSegmentedColormap

Examples:

>>> from pyhelpers.viz import cmap_discretization
>>> from pyhelpers.settings import mpl_preferences
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> mpl_preferences()
>>> cm_accent = cmap_discretization(cmap=plt.colormaps['Accent'], n_colors=5)
>>> cm_accent.name
'Accent_5'
>>> cm_accent = cmap_discretization(cmap='Accent', n_colors=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/viz-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 23:

../_images/viz-cmap_discretization-demo.svg

Figure 23 An example of discrete colour ramp, created by the function cmap_discretization().