Search code examples
matlabmatlab-figurecolormap

How to save a custom colormap and use it again in Matlab?


I have created a colormap that resembles the human connectome project colormap ROY-BIG-BL, doing it manually on the colormap editor see here.

However, I am not able to save this as a colormap. I tried different commands such as

mycmap = get(gcf,'colormap')

I read that with Matlab 2015 one should use gca, but this gives an error.

Error using matlab.graphics.axis.Axes/get There is no colormap property on the Axes class.

When I then try to use the saved mycmap for another figure, it ignores all modifications und uses the basic colormap parula.

Thanks for help. How can I save it and use it as another colormap in any figure I want?


Solution

  • The definition of colormaps is deeply hidden inside the figure class, which is not accessible. So you can't save your colormap "with a name" in Matlab and access it like a normal colormap. But a colormap is nothin else than a Yx3 matrix, you can store on disk.

    %// custom colormap
    n = 50;               %// number of colors
    R = linspace(1,0,n);  %// Red from 1 to 0
    B = linspace(0,1,n);  %// Blue from 0 to 1
    G = zeros(size(R));   %// Green all zero
    myCustomColormap = [R(:), G(:), B(:)];
    
    %// save colormap on disk
    save('myCustomColormap','myCustomColormap');
    
    %// clear for explanation purposes
    clear 
    %%%%%%%%%%%%%%%%%%%
    
    %// load colormap saved on disk
    load myCustomColormap
    
    %// assign colormap
    colormap( myCustomColormap ); 
    

    You used the colormap editor to create your colormap. After you applied it, use the following code to get the required matrix for further reference:

    myCustomColormap = colormap(gca)
    save('myCustomColormap','myCustomColormap');
    

    If you want to make the colormap generally available to all your functions, no matter where, add it to your Matlab search path.