matlabmatlab-figurecolorbarcolor-mappingmatlab-hg2

Manipulating underlying image data of colorbar in Matlab


In matlab versions prior to 2014 I could alter the underlying image in the colorbar by doing the following:

cmap = ... % something which is MxNx3
colormap(reshape(cmap, [N*M,3]))
cmapIxs2D = reshape((1:(N*M))', [N, M]);
ax = colorbar('peer', gca);
set(get(ax, 'Children'), 'CData', cmapIxs2D);
ylim(ch, [0 255]), xlim(ch, [0 1])

This was useful if you wanted to display a custom colormap which is e.g. 2D (NxMx3) instead of the normal 1D (Nx3). How could this be done in versions after 2014 where the underlying image of the colorbar is no longer accesible, it has no Children according to the documentation.

Example (Color value is interpreted as having a e.g. velocity(y-axis-color) and acceleration(x-axis-color)) :

enter image description here


Solution

  • Based on the ideas proposed in the OP comments, I've come up with something:

    function q38871518
    %% Plot something random:
    hF = figure('Color',0.4*[1 1 1],'SizeChangedFcn',@recolorCB); membrane;
    hTmp = gca;
    % Compute the fake colorbar contents:
    cm = bsxfun(@times,permute(colormap,[1,3,2]),0:0.01:1); % figure(); imagesc(cm);
    % Create an axes to hold the fake colorbar
    hAx = axes(hF); imagesc(hAx,cm); axis(hAx,'off'); 
    function recolorCB(varargin)
      drawnow;
      if exist('cb','var')
        cb.Face.Texture.CData(:) = 0;
        % "Link" the 'Position' prop between the colorbar and the fake colorbar:
        hAx.Position = cb.Position;
      end
    end
    % Create the real colorbar 
    cb = colorbar(hTmp,'Color',[1 1 1]);
    % Synchronize positions:
    hAx.Position = cb.Position;
    % Make sure the fake colorbar is at the bottom, so we can see the values clearly
    uistack(hAx,'bottom');
    % Final touch-ups:
    drawnow; cb.Face.Texture.CData(:) = 0; cb.Face.Texture.ColorType = 'truecoloralpha';
    end
    

    The result is:

    enter image description here

    The "fake" colorbar moves to the correct location as the figure size changes. When saving the figure, the old colorbar appears, this also happens after zooming out (and probably following some other actions). Getting rid of this would require some extra hacking...

    Tested on MATLAB R2016a.