Search code examples
matlabplotmatlab-figurelegendcolorbar

How to place a colorbar in Matlab plot legend Icon


I visualize map overlays in Matlab with some surfaces with RGB texture. It looks like this:

matlab

I would like to have better Legend icons that make clear which layer is which. Something like this:

Gimp

While I just did the second one in Gimp, I would like to have it in code.

Is it possible? It would be OK to use something from Matlab File Exchange or so.


Solution

  • One option will be to 'draw' this part of the legend manually after you create the figure. Here is how you can do this:

    plot(nan(2)) % this is to make space in the legend box
    hold on
    plot(rand(15,1),'r') % here you plot all your data
    hold off
    hleg = legend({'Lidar Map','Radar Reprojection','Robot Path'});
    % get the position of the legend, and calculate the place for the colormaps:
                        % this values may need to be adjusted
    pos = hleg.Position.*[1.01 1+hleg.Position(4)/2.3 0.27 0.6]; 
    % Create a 'picture' of what you want to appear in the legend:
    level = 64; % level of color in the colormaps
    cb = [1:level;    zeros(1,level);    (1:level)+level];
    cmap = [1 1 1;0 0 0;flipud(gray(level-1)); jet(level)]; % custom colormap
    legax = axes('Position',pos); % place the new picture above the legend
    imagesc(legax,repelem(cb,[3 1 3],1)) % Create the picture
    colormap(cmap) % appy custom colormap
    axis off % remove all axes details
    

    Here is the result:

    enter image description here

    The problem here is that the custom color map of the legend may interfere with the color map of the data itself, so you may need to take care of that also, but I can't tell you how without knowing how your data looks like and how do you currently apply the colormaps.