How can I turn a NumPy array into a MatPlotLib colormap?

matplotlib, python

Solution

I suggest this function that converts a Nx3 numpy array into a colormap

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors

#-----------------------------------------
def array2cmap(X):
    N = X.shape[0]

    r = np.linspace(0., 1., N+1)
    r = np.sort(np.concatenate((r, r)))[1:-1]

    rd = np.concatenate([[X[i, 0], X[i, 0]] for i in xrange(N)])
    gr = np.concatenate([[X[i, 1], X[i, 1]] for i in xrange(N)])
    bl = np.concatenate([[X[i, 2], X[i, 2]] for i in xrange(N)])

    rd = tuple([(r[i], rd[i], rd[i]) for i in xrange(2 * N)])
    gr = tuple([(r[i], gr[i], gr[i]) for i in xrange(2 * N)])
    bl = tuple([(r[i], bl[i], bl[i]) for i in xrange(2 * N)])


    cdict = {'red': rd, 'green': gr, 'blue': bl}
    return colors.LinearSegmentedColormap('my_colormap', cdict, N)
#-----------------------------------------
if __name__ == "__main__":

    #define the colormar
    X = np.array([[0., 1., 0.],  #green
                  [0., 0., 1.],  #blue
                  [1., 1., 0.],  #yellow
                  [1., 0., 0.]]) #red
    mycmap = array2cmap(X)

    values = np.random.rand(10, 10)
    plt.gca().pcolormesh(values, cmap=mycmap)

    cb = plt.cm.ScalarMappable(norm=None, cmap=mycmap)
    cb.set_array(values)
    cb.set_clim((0., 1.))
    plt.gcf().colorbar(cb)
    plt.show()

will produce :

Problem

I am trying to create a color map of 4 different colors. I have a NumPy array, and there are 4 values in that array: 0, .25, .75, and 1. How can I make MatPlotLib plot, for instance, green for 0, blue for .25, yellow for .75, and red for 1? Thanks!

Original source