Display discrete value for color

I am trying to create a pcolor based on 4 discrete values ​​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 this?

test = ([1,2,2,1,3],[1,1,1,1,4],[2,1,1,2,1])
import numpy as np

dataset = np.array(test)
plt.pcolor(dataset)

      

Thank,

+3


source to share


2 answers


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

The minimum and maximum C elements are assigned the first and last colors in the color palette. The colors for the remaining elements in C are linearly mapped from value to colormap.

Instead, you can try imshow

and use dict

to display 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 in test]
plt.imshow(test_rgb, interpolation = 'none')

      

enter image description here

+5


source


According to this document, you can create colors like this

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

      

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

will 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 0.0, top right 1.0. pcolor takes actual colors from the gradient. I've used the gnuplot gradient here. So 0.0 is the color to the left of the gradient, 1.0 is the color to the right.

If you need specific colors, you can define your own gradient. This is a good tutorial on color maps.

+2


source







All Articles