Home > database >  Get hex colors of discrete colorbar
Get hex colors of discrete colorbar

Time:09-13

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!

CodePudding user response:

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']

CodePudding user response:

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).

  • Related