color_bar_index¶
- pyhelpers.viz.color_bar_index(cmap, n_colors, labels=None, **kwargs)[source]¶
Creates a color bar with correctly aligned labels.
Note
To avoid off-by-one errors, this function takes a standard colormap, discretizes it, and then draws a color bar with labels aligned correctly.
See also [VIZ-CBI-1].
- Parameters:
cmap (matplotlib.colors.ListedColormap | matplotlib.colors.Colormap) – A colormap instance, e.g. built-in colormaps accessible via matplotlib.cm.get_cmap().
n_colors (int) – Number of discrete colors to use in the color bar.
labels (list | None) – Optional list of labels for the color bar; defaults to
None
.kwargs – [Optional] Additional optional parameters for the matplotlib.pyplot.colorbar() function.
- Returns:
A color bar object.
- Return type:
matplotlib.colorbar.Colorbar
Examples:
>>> from pyhelpers.viz import color_bar_index >>> from pyhelpers.settings import mpl_preferences >>> import matplotlib.pyplot as plt >>> mpl_preferences() >>> fig1 = plt.figure(figsize=(2, 6), constrained_layout=True) >>> ax1 = fig1.add_subplot() >>> cbar1 = color_bar_index(cmap=plt.colormaps['Accent'], n_colors=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/viz-color_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 24:
Figure 24 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 = color_bar_index(cmap=plt.colormaps['Accent'], n_colors=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/viz-color_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 25:
Figure 25 An example of colour bar with textual index.¶