Search code examples
matlabvisualizationdata-visualizationmatlab-figurecolormap

How to use only a part of an existing colormap?


I am using colormap to visualize some data:

DataToPlot = pcolor(myData);
set(DataToPlot,'edgecolor','none'); %to remove grid
colormap(flipud(spring));
caxis([-4 4]);
colorbar;

At the moment the colour associated with the value -4 is yellow, and the colour associated with +4 is bright pink. I would like to modify this scale and have as colour associated with -4 what is now the colour for 0 (which is a light pink), and leaving the colour associated with +4 as the bright pink.

How can I do this?


Solution

  • Let's consider the following example:

    figure(); imagesc(magic(4)-8); colorbar;
    % Flipped "spring" colormap:
    cm = flipud(spring); colormap(cm);
    

    Now we have:

    Flipped <code>spring</code>

    If we want only a subset of the colormap (e.g. yellow to pink) we can take a subset of the rows of the array returned by spring:

    cm = flipud(spring(200)); colormap(cm(1:100,:));
    

    where 200 is the resolution of the colormap we want to get, and 100 is approximately the position of the map where we want to cut, yielding:

    First half of the flipped <code>spring</code>

    If we want to rescale the colormap (or in other words change the mapping of data to colors such that the min/max value does not correspond to the bottom/top color), we can use caxis function to set different limits for the colormap. For example:

    cm = flipud(spring); colormap(cm); caxis([-7 24]);
    

    yields the same data coloring using the complete colormap:

    Rescaled colormap

    Bonus: don't forget you can also combine different colormaps:

    cm = [flipud(bone(50)); copper(50)]; colormap(cm);
    

    enter image description here