Search code examples
matlabmatlab-figurecolormap

How to define transparent element in colormap


I would like to define a transparent color within the color map how do I do that?

The reason I need this is that I have a multiple layers in my axes (produced both by imagesc and plot). I know I could simply first use imagesc and then plot but I want to draw the lines behind non-zero values of the imagesc representation.

To color the zeros white I use

jet = colormap('jet');
jet(1:2,:) = 1;
colormap(jet);

Now I would like to make white transparent.


Solution

  • The colormap doesn't have a fourth element for alpha, it's RGB only, so the way I do this sort of thing is to make a mask of the desired transparency layer - binary or greyscale will work - and then apply that to the image. To do this you need to store the handle of the image

    % make random image
    im = rand(100,100);
    % make example alphamask
    alphamask = im<0.3;
    % store handle
    hnd = imagesc(im);
    % apply mask
    set(hnd, 'AlphaData', alphamask);