James Warner February 2016

Custom Colorbar

I'm trying to create a custom colorbar, but the colorscale looks completely different to what I'm defining - enter image description here

The color should be going from brown -> white -> blue, There should be 9 categories.

My code is attached below:

plot = np.clip(plot,40,250)

bounds = [0, 40, 60, 80, 100, 125, 150, 200, 250, 300]
rgblist = [(51,25,0), (102,51,0), (153,76,0), (239,159,80), (255, 255, 255),
       (153,204,255), (51,153,255), (0,102,204), (2,2,128)]
clist = [[c/255 for  c in rgb] for rgb in rgblist]
cmap = colors.ListedColormap(clist)
norm = colors.BoundaryNorm(bounds, cmap.N)


cs = m.contourf(X,Y,plot,bounds, cmap=cmap, norm=norm)
cbar = m.colorbar(cs, ticks=[20,50,70,90,112.5,137.5,175,225,275])
cbar.set_ticklabels(['<40','40-60', '60-80', '80-100', '100-125', '125-150', '150-200', '200-250', '>250'])

plt.show()

Answers


Christoph February 2016

I guess that you are using Python 2.x. In that case, your line

clist = [[c/255 for  c in rgb] for rgb in rgblist]

is performing integer division, i.e. the result is stored as an integer and all fractional information is lost. In your case, this leads to all divisions except 255/255 resulting in 0.

To change this, you can either divide by a float by just adding the decimal point:

clist = [[c/255. for  c in rgb] for rgb in rgblist]

Or you can import the Python 3 division behaviour before the division via

from __future__ import division

Post Status

Asked in February 2016
Viewed 1,702 times
Voted 7
Answered 1 times

Search




Leave an answer