Home > Enterprise >  How to create custom standalone matplotlib colorbar with labels?
How to create custom standalone matplotlib colorbar with labels?

Time:12-04

I want to create a custom and standalone matplotlib colorbar with text labels. However, I couldn't assign the labels to the colors in colorbar correctly. How can I assign text labels to each color in colorbar with matplotlib?

import matplotlib.colorbar as colorbar
import matplotlib.colors as clr
import matplotlib.pyplot as plt

cb_colors = ["#000000", "#808000", "#D3D3D3", "#FFFFFF", "#000080", "#FF4500", "#696969", "#FFFFE0"]
cmap_ = clr.ListedColormap(cb_colors)

fig = plt.figure()
ax = fig.add_axes([0.05, 0.80, 0.9, 0.1])

cb = colorbar.ColorbarBase(ax, orientation='horizontal', 
                               cmap=cmap_)

cb.ax.set_xticks([0, 1, 2, 3, 4, 5, 6, 7])
cb.ax.set_xticklabels(["A", "B", "C", "D", 
                       "E", "F", "G", "H"])

enter image description here

P.S.: Even I have changed code to the below one it didn't solve my problem.

cb.set_ticks([0, 1, 2, 3, 4, 5, 6, 7])
cb.set_ticklabels(["A", "B", "C", "D", 
                       "E", "F", "G", "H"])

enter image description here

CodePudding user response:

The default internal numbering is from 0 to 1. A tick at a position larger than 1 will not be visible. The internal numbering can be changed via a colorbar with labels at the center of the colors

If you need to keep the default range 0 to 1, you could use cb.set_ticks(np.linspace(0, 1, 2*num_colors 1)[1::2]). This divides the range into 17 equally spaced positions and would use the odd ones for the ticks.

  • Related