colour_bar_index

pyhelpers.ops.colour_bar_index(cmap, n_colours, labels=None, **kwargs)[source]

Create a colour bar.

To stop making off-by-one errors. Takes a standard colour ramp, and discretizes it, then draws a colour bar with correctly aligned labels.

See also [OPS-CBI-1].

Parameters:
  • cmap (matplotlib.colors.ListedColormap) – a colormap instance, e.g. built-in colormaps that is accessible via matplotlib.cm.get_cmap

  • n_colours (int) – number of colours

  • labels (list | None) – a list of labels for the colour bar, defaults to None

  • kwargs – [optional] parameters of matplotlib.pyplot.colorbar

Returns:

a colour bar object

Return type:

matplotlib.colorbar.Colorbar

Examples:

>>> from pyhelpers.ops import colour_bar_index
>>> from pyhelpers.settings import mpl_preferences

>>> mpl_preferences(backend='TkAgg', font_name='Times New Roman')

>>> import matplotlib
>>> import matplotlib.pyplot as plt

>>> fig = plt.figure(figsize=(2, 6), constrained_layout=True)
>>> ax = fig.add_subplot()

>>> cbar = colour_bar_index(cmap=matplotlib.colormaps['Accent'], n_colours=5)

>>> ax.tick_params(axis='both', which='major', labelsize=14)
>>> cbar.ax.tick_params(labelsize=14)

>>> # ax.axis('off')
>>> plt.show()

The above example is illustrated in Fig. 4:

../_images/ops-colour_bar_index-demo-1.svg

Fig. 4 An example of colour bar with numerical index, created by the function colour_bar_index().

>>> fig = plt.figure(figsize=(2, 6), constrained_layout=True)
>>> ax = fig.add_subplot()

>>> labels_ = list('abcde')
>>> cbar = colour_bar_index(matplotlib.colormaps['Accent'], n_colours=5, labels=labels_)

>>> ax.tick_params(axis='both', which='major', labelsize=14)
>>> cbar.ax.tick_params(labelsize=14)

>>> # ax.axis('off')
>>> plt.show()

This second example is illustrated in Fig. 5:

../_images/ops-colour_bar_index-demo-2.svg

Fig. 5 An example of colour bar with textual index, created by the function colour_bar_index().

>>> plt.close(fig='all')