Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 853
NumberOneRobot Avatar asked Jul 06 '12 15:07

NumberOneRobot


People also ask

Can Matplotlib plot NumPy array?

We can use it along with the NumPy library of Python also. NumPy stands for Numerical Python and it is used for working with arrays. The following are the steps used to plot the numpy array: Defining Libraries: Import the required libraries such as matplotlib.


1 Answers

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 : enter image description here

like image 121
user2660966 Avatar answered Oct 13 '22 07:10

user2660966