squarerootnegative1
squarerootnegative1

Reputation: 33

Create a colormap that is assigned to specific integer values with numpy/scipy

I am looking for way to create a colormap in python/matplotlib that is specific to a designated integer value and remains that integer value. Here is an example of how I define the matlab colormap:

c_map = [1   1   1;...     % Integer assignment = 0 - Air - white
         0.6 1 0.8;... % Integer assignment = 1 - Water - cyan
         1 0.6 0.2];   % Integer assignment = 2 - Sediments - orange

it is later called during the plotting routine by:

colormap(c_map);
pcolor(xvec,zvec,ColorIntegers);
shading interp, colormap, caxis([0 3]), axis ij

The integer values always stay the same (i.e., Air = 0 , Water = 1, sediments = 2).

I've scoured the matplotlib documentation and stack, but haven't found a way to create this specific style colormap, which relates corresponding integers to a color. Most questions deal with diverging, jet, centering, linear, non-linear as opposed to a consistent coloring of specific colormaps. Each color must correspond to that specific integer value.

Any help will be appreciated, thank you in advance.

Upvotes: 3

Views: 2405

Answers (1)

Warren Weckesser
Warren Weckesser

Reputation: 114811

Take a look at the ListedColormap.

For example,

In [103]: y
Out[103]: 
array([[1, 1, 2, 2, 2, 1, 0, 0, 0, 1, 2, 2, 2, 2, 2, 1],
       [1, 1, 1, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0],
       [1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 0],
       [1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 2, 2, 2, 2, 1, 0],
       [1, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 3, 3, 2, 1, 0],
       [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1],
       [1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 1],
       [1, 1, 0, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1],
       [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1],
       [0, 1, 1, 1, 2, 2, 2, 2, 2, 3, 2, 1, 1, 1, 1, 2],
       [0, 1, 2, 2, 2, 2, 2, 2, 2, 3, 2, 2, 1, 1, 2, 2],
       [1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 2, 2, 2, 2, 2],
       [2, 1, 1, 0, 0, 1, 2, 2, 3, 3, 3, 2, 2, 2, 2, 1],
       [2, 1, 1, 0, 1, 2, 2, 3, 3, 3, 3, 2, 1, 1, 1, 1],
       [2, 1, 1, 0, 2, 3, 3, 3, 3, 3, 2, 1, 0, 1, 1, 0]])

In [104]: c_map = [[1, 1, 1], [0.6, 1, 0.8], [1, 0.6, 0.2], [0.75, 0.25, 0.25]]

In [105]: cm = matplotlib.colors.ListedColormap(c_map)

In [106]: imshow(y, interpolation='nearest', cmap=cm)

generates

image

Upvotes: 5

Related Questions