colour_bar_index

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

Create a colour bar with correctly aligned labels.

Note

  • To avoid off-by-one errors, this function takes a standard colour ramp, discretizes it, and then draws a colour bar with labels aligned correctly.

  • See also [OPS-CBI-1].

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

  • n_colours (int) – Number of discrete colours to use in the colour bar.

  • labels (list | None) – Optional list of labels for the colour bar; defaults to None.

  • kwargs – [Optional] Additional optional parameters for the funtion 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')
>>> import matplotlib.pyplot as plt
>>> fig1 = plt.figure(figsize=(2, 6), constrained_layout=True)
>>> ax1 = fig1.add_subplot()
>>> cbar1 = colour_bar_index(cmap=plt.colormaps['Accent'], n_colours=5)
>>> ax1.tick_params(axis='both', which='major', labelsize=14)
>>> cbar1.ax.tick_params(labelsize=14)
>>> # ax.axis('off')
>>> fig1.show()
>>> # from pyhelpers.store import save_figure
>>> # path_to_fig1_ = "docs/source/_images/ops-colour_bar_index-demo-1"
>>> # save_figure(fig1, f"{path_to_fig1_}.svg", verbose=True)
>>> # save_figure(fig1, f"{path_to_fig1_}.pdf", verbose=True)

The above example is illustrated in Figure 9:

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

Figure 9 An example of colour bar with numerical index.

>>> fig2 = plt.figure(figsize=(2, 6), constrained_layout=True)
>>> ax2 = fig2.add_subplot()
>>> labels_ = list('abcde')
>>> cbar2 = colour_bar_index(cmap=plt.colormaps['Accent'], n_colours=5, labels=labels_)
>>> ax2.tick_params(axis='both', which='major', labelsize=14)
>>> cbar2.ax.tick_params(labelsize=14)
>>> # ax.axis('off')
>>> fig2.show()
>>> # path_to_fig2_ = "docs/source/_images/ops-colour_bar_index-demo-2"
>>> # save_figure(fig2, f"{path_to_fig2_}.svg", verbose=True)
>>> # save_figure(fig2, f"{path_to_fig2_}.pdf", verbose=True)

This second example is illustrated in Figure 10:

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

Figure 10 An example of colour bar with textual index.