Get hex colors of discrete colorbar

Question:

I have the following colorbar :

from matplotlib import cm

cmap = matplotlib.cm.Blues
bounds = [0, 500, 1000, 1500, 2000, 2500]
norm = matplotlib.colors.BoundaryNorm(bounds, cmap.N , extend = 'max')
plt.colorbar(matplotlib.cm.ScalarMappable(norm=norm, cmap=cmap), orientation='vertical')

Is there a way to get the hex codes of the six colors generated?

Thanks!

Asked By: zorals

||

Answers:

You could save the file as a JPG or PNG using the savefig() function in matplotlib. To find the hex codes, you can input the PIL library. The function PIL.ImageColor.getrgb() could then be used. (Of course, you first would have to use from PIL import ImageColor).

Answered By: Galactic Eagle

The norm object has a property boundaries – normalise those to the original cmap range, then cmap can convert those to RGBA 4-tuples, and then you can call matplotlib.colors.rgb2hex. Putting it all into a list comprehension gets you:

[matplotlib.colors.rgb2hex(cmap(norm(c))) for c in norm.boundaries]

Result:

['#f7fbff', '#d0e1f2', '#94c4df', '#4a98c9', '#1764ab', '#08306b']
Answered By: Josh Friedlander
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.