Search code examples
matlabcolorbarcolormap

Display colorbars for multiple colormaps in MATLAB


I have an image that I want to display in MATLAB and overlay some data (a separate image). I am using two different colormaps for these two images, but can't seem to get two colorbars. A colorbar that contains both maps would also be okay. This is my code so far:

close all; clc;

figure(1)
im1 = ind2rgb( gray2ind(mat2gray(f,[.1 1]),256), spring(256));
h1  = imshow(  im1, [.1 1] );

hold on; 

colorbar 

FA(isnan(FA))  = 0;
alpha          = ones( size(f) );
alpha(mapvis)  = 0;
im2            = ind2rgb( gray2ind(mat2gray(FA,[0 1]),256), bone(256));
h2             = imshow(  im2, [0 1] );
set(h2, 'AlphaData', alpha);

colorbar
hold off

%cdata1 = h1.CData;
%cdata2 = h2.CData;
%cc = [cdata1; cdata2];

(I included some comments as i tried to concatenate the colormaps, by following this example without luck: https://se.mathworks.com/matlabcentral/answers/101346-how-do-i-use-multiple-colormaps-in-a-single-figure#Example_1) which results in the following plot: Resulting plot. Which isn't quite what i am looking for.


Solution

  • Here's one way to have multiple colormaps on a single figure. The idea is to overlay multiple Axes objects on top of each other, make the Axes background transparent so their plots overlay each other. This only works well for 2D view. In 3D view, plots/surfaces will overlap each other incorrectly.

    clear all;
    close all;
    clc;
    
    ax = gca;
    ax(2) = copyobj(ax, ax.Parent);
    linkprop(ax, {'XLim', 'YLim', 'ZLim', 'Position', 'View'});
    
    [x, y, z] = peaks;
    
    % plot onto first axes
    pcolor(ax(1), x, y, z);
    shading(ax(1), 'interp')
    
    % plot onto second axes, arbitrarily shifting the data to a new range
    contour(ax(2), x, y, -z+10, 10);
    
    % set the colormap and CLims of each axes
    set(ax(1), 'CLim', [-10, 10], 'Colormap', parula);
    set(ax(2), 'CLim', [0, 20], 'Colormap', bone);
    
    % Make the second axes invisible
    set(ax(2), 'Color', 'None', 'XColor', 'none', 'YColor', 'none', 'ZColor', 'none');
    
    % make the colorbars
    cb(1) = colorbar(ax(1), 'East');
    cb(2) = colorbar(ax(2), 'South');
    

    You will have to manually adjust the Colorbar and Axes Positions as you see fit.

    enter image description here