Skip to content Skip to sidebar Skip to footer

Map Discrete Value To Color

I am trying to create pcolor based on 4 discrete value 1, 2, 3, 4. I want to define 1 as black, 2 as red, 3 as yellow and 4 as green. does anyone know how to do it? test = ([1,2,2,

Solution 1:

I don't think you want to use pcolor. From the Matlab docs (presumably the matplotlib pcolor does the same thing):

The minimum and maximum elements of C are assigned the first and last colors in the colormap. Colors for the remaining elements in C are determined by a linear mapping from value to colormap element.

You could try imshow instead, and use a dict to map the colors you want:

colordict = {1:(0,0,0),2:(1,0,0),3:(1,1,0),4:(0,1,0)}
test = ([1,2,2,1,3],[1,1,1,1,4],[2,1,1,2,1])
test_rgb = [[colordict[i] for i in row] for row intest]
plt.imshow(test_rgb, interpolation = 'none')

enter image description here

Solution 2:

According to this doc, you can create colors like this

red = (1, 0, 0)    # This would be redgreen = (0, 1, 0)  # this is green

So colors = ((0, 0, 0), (1, 0, 0), (0, 1, 0))

would give you colors[1] red, and colors[2] green.

This program shows how pcolor works:

import pylab as plt
import numpy as np

def test_pcolor():
    cmap = plt.get_cmap('gnuplot')
    Z = np.empty((100, 100))
    for x in range(100):
        for y in range(100):
            Z[y, x] = 0.0001 * x * y

    plt.subplot(1,1,1)
    c = plt.pcolor(Z, cmap = cmap)

    plt.show()

def main():
    test_pcolor()
    return 0

if __name__ == '__main__':
    main()

Bottom left is 0.0, top right is 1.0. pcolor takes the actual colors from a gradient. I've used the gnuplot gradient here. So 0.0 is the color left of the gradient, 1.0 is the color at the right.

If you want particular colors, you can define your own gradient. This is a nice tutorial on colormaps.

Post a Comment for "Map Discrete Value To Color"