Search code examples
matlabalphacolorbar

Setting alpha of colorbar in MATLAB R2015b


I would like to set some transparency in my plot which I can do with alpha. This works great but I also want to adapt the colorbar. Here is an example:

subplot(2,1,1)
A = imagesc(meshgrid(0:10,0:5));
alpha(A,1)
colorbar

subplot(2,1,2)
B = imagesc(meshgrid(0:10,0:5));
alpha(B,.1)
colorbar

The example is taken from here. On this page two solutions exists but none works for Matlab R2015b.

enter image description here


Solution

  • With HG2 graphics (R2014b+) you can get some of the undocumented underlying plot objects and alter the transparency.

    c = colorbar();
    
    % Manually flush the event queue and force MATLAB to render the colorbar
    % necessary on some versions
    drawnow
    
    alphaVal = 0.1;
    
    % Get the color data of the object that correponds to the colorbar
    cdata = c.Face.Texture.CData;
    
    % Change the 4th channel (alpha channel) to 10% of it's initial value (255)
    cdata(end,:) = uint8(alphaVal * cdata(end,:));
    
    % Ensure that the display respects the alpha channel
    c.Face.Texture.ColorType = 'truecoloralpha';
    
    % Update the color data with the new transparency information
    c.Face.Texture.CData = cdata;
    

    enter image description here

    You have to be careful doing this as the colorbar is continually refreshed and these changes will not stick. To get them to stay while I printed the figure, I just changed the ColorBinding mode of the Face to something besides interpolated

    c.Face.ColorBinding = 'discrete';
    

    This means that it won't be updated when you change color limits or the colormap. If you want to change either of those things you'll need to reset the ColorBinding to intepolated and then run the above code again.

    c.Face.ColorBinding = 'interpolated';
    

    For example, the following would save an image with a transparent colorbar for two colormaps:

    c = colorbar();
    
    drawnow;
    
    alphaVal = 0.1;
    
    % Make the colorbar transparent
    cdata = c.Face.Texture.CData;
    cdata(end,:) = uint8(alphaVal * cdata(end,:));
    c.Face.Texture.ColorType = 'truecoloralpha';
    c.Face.Texture.CData = cdata;
    
    drawnow
    
    % Make sure that the renderer doesn't revert your changes
    c.Face.ColorBinding = 'discrete';
    
    % Print your figure
    print(gcf, 'Parula.png', '-dpng', '-r300');
    
    % Now change the ColorBinding back
    c.Face.ColorBinding = 'interpolated';
    
    % Update the colormap to something new
    colormap(jet);
    
    drawnow
    
    % Set the alpha values again
    cdata = c.Face.Texture.CData;
    cdata(end,:) = uint8(alphaVal * cdata(end,:));
    c.Face.Texture.CData = cdata;
    
    drawnow
    
    % Make sure that the renderer doesn't revert your changes
    c.Face.ColorBinding = 'discrete';
    
    print(gcf, 'Ugly_colormap.png', '-dpng', '-r300');