Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map integers to colors in matplotlib? [duplicate]

Update: Did a lousy hack where I choose a colormap gradient ('nipy_spectral' in my case) and make a dictionary that maps the color I want to an integer such that the plotting function will plot the correct color. It involves a lot of futzing around with the numbers. I'll post as solution if nothing better comes along.


I have the following plotting function adapted from another plotting function I used for a confusion matrix:

def plot_matrix(rm, title='Robot World', cmap=plt.cm.Blues):
    plt.imshow(rm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.tight_layout()

And I have a matrix of the following form:

[ 1,3,1,0,1,3,4]

[ 3,1,0,1,2,3,0]

... for a few more rows.

Ideally, I plot this matrix such that the integer values within the matrix correspond to the colors: ['black','blue','yellow','green','red'] in a plot that looks something like the example matrix on matplotlib's example site for interpolation nearest:

enter image description here


I think the answer must be some kind of custom cmap, like:

cmap = { 0:'k',1:'b',2:'y',3:'g',4:'r' }

How would I do this in matplotlib? I am looking at the custom colormap site, and it seems a whole lot more involved than what I am trying to do...

like image 881
Chris Avatar asked Apr 02 '16 19:04

Chris


People also ask

How do I specify colors on a Matplotlib plot?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

How do I specify RGB in Matplotlib?

Matplotlib recognizes the following formats to specify a color. RGB or RGBA (red, green, blue, alpha) tuple of float values in a closed interval [0, 1]. Case-insensitive hex RGB or RGBA string. Case-insensitive RGB or RGBA string equivalent hex shorthand of duplicated characters.

Can we select Colours of the visualization using Matplotlib?

With matplotlibYou can pass plt. scatter a c argument, which allows you to select the colors.


1 Answers

You can use a ListedColormap to do a discrete colormap:

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

def plot_matrix(rm, title='Robot World', cmap=plt.cm.Blues):
    plt.imshow(rm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.tight_layout()
    plt.show()

cmap = colors.ListedColormap(['k','b','y','g','r'])
rm = np.random.randint(0,4,(5,5))
plot_matrix(rm,cmap=cmap)

, the result is this:

ListedColormap example

like image 68
armatita Avatar answered Oct 07 '22 01:10

armatita