Setting custom color in pseudocolor plot using matplotlib

Possible duplicate:
Add separate colors for two (or more) specific values โ€‹โ€‹in the color scheme and color bar

I have an array of values โ€‹โ€‹and I would like to build them using pcolor in matplotlib. I use the "YlOrRd" color map and it works fine, but I would like to use the color map for all non-zero values. That is, all values โ€‹โ€‹other than 0 should use a color map - I would like 0 to be black.

I am currently using the "x" values โ€‹โ€‹for my numpy array.

pcolor(x,cmap=cm.YlOrRd) 

Is there a way to arbitrarily fix all values โ€‹โ€‹in an array of x that are 0 to black?

Thanks, Dave.

+6
source share
1 answer

Here are two ways to do this. One of them created its own colormap , and the other using masked array . Say we have:

 import matplotlib from pylab import * data = np.arange(-50, 50).reshape(10, 10) data = np.abs(data) pcolor(data, cmap=cm.YlOrRd) show() 

This gives: enter image description here Now we do the same, but create a list called colors that has the same values โ€‹โ€‹as cm.YlOrRd , except for the entry 0 , which we set to black ( 0,0,0 in rgb). Then we use LinearSegmentedColormap.from_list to actually create the color map:

 import matplotlib from pylab import * data = np.arange(-50, 50).reshape(10, 10) data = np.abs(data) colors = [(0,0,0)] + [(cm.YlOrRd(i)) for i in xrange(1,256)] new_map = matplotlib.colors.LinearSegmentedColormap.from_list('new_map', colors, N=256) pcolor(data, cmap=new_map) savefig('map.png') show() 

This gives the same plot, but zero values โ€‹โ€‹are black:

enter image description here Another way to use masked arrays, its a bit more involved, comments in the code explain the steps:

 from pylab import * import numpy.ma as ma data=np.arange(-50,50).reshape(10,10) data=np.abs(data) #create a mask where only values=0 are true: mask = data == 0 #create a masked array by combining our mask and data: mx = ma.masked_array(data, mask) #set masked values in cm.YlOrRd to 'black' cm.YlOrRd.set_bad(color='black', alpha=None) # pcolor(data,cmap=cm.YlOrRd) #we must use pcolormesh instead of pcolor, as pcolor does not draw masked values at all pcolormesh(mx,cmap=cm.YlOrRd) show() 

Gives the same schedule as above.

There is a potential difference between these methods, the first method rounds up the data values โ€‹โ€‹and applies the corresponding color, while the second method sets the values โ€‹โ€‹equal to 0 to black (that is, 0.001 will not be masked, be the appropriate color cm.YlOrRd ). The main advantage of the second is that you can mask recordings completely arbitrarily.

+5
source

Source: https://habr.com/ru/post/915363/


All Articles