Search code examples
matlabplotpngcolorbar

Matlab: Plot colourful line over background gray image whilst retaining colorbar information


I am using MATLAB I would like to plot a colourful trajectory on top of a grayscale png image whilst retaining the colour information of the trajectory. For example with the data below, I would like to plot Data B over Image A. Without Data B turning gray and without making the colourbar represent the grayscaled image. Any help would be greatly appreciated!

%Image A
RGB = imread('peppers.png');
I = rgb2gray(RGB);
figure
imshow(I)

hold on

%Data B
x = 1:1000; 
y = x;
z = zeros(size(x));
lineColor = x; 
surface([x;x], [y;y], [z;z], [lineColor;lineColor],...
    'FaceColor', 'no',...
    'EdgeColor', 'interp',...
    'LineWidth', 8);
cc = colorbar();

Many thanks!


Solution

  • MATLAB doesn't seem to like to do more than one colourmap pet axes. By using hold on we're plotting both the image (gray colormap) and surface (e.g. jet colormap) to the same plot. By default from the non-RGB image in imshow the colormap is set to gray, and so it is the same for the surface plot. Trying to change the colourmap by invoking colormap('jet') changes the colormap for both the image and surface.

    Seems that there have been others with the same problem: https://uk.mathworks.com/matlabcentral/answers/194554-how-can-i-use-and-display-two-different-colormaps-on-the-same-figure

    The best solution appears to be defining two seperate axes to the same figure and linking them so that positional information matches. You need to specify which axis to plot to, so imshow has been replaced with imagesc which has more flexibility.Then you can define a different colourmap to each axis. Unfortunately, the colorbar probably won't play ball everytime so you gotta fiddle with its positional information a bit.

    In practice for your code:

    figure
    
    %Image A
    ax1 = axes;
    RGB = imread('peppers.png');
    I = rgb2gray(RGB);
    imagesc(ax1,I)
    colormap(ax1,'gray')
    
    
    %Data B
    ax2 = axes;
    ax2.Visible = 'off'; % make transparent
    x = 1:1000; 
    y = x;
    z = zeros(size(x));
    lineColor = x; 
    h = surface(ax2, [x;x], [y;y], [z;z], [lineColor;lineColor],...
        'FaceColor', 'no',...
        'EdgeColor', 'interp',...
        'LineWidth', 8);
    colormap(ax2,'jet') % colourful colourmap
    % Gotta reposition the colourbar, tedious bit!
    % Position: [left bottom width height]
    cb2 = colorbar(ax2,'Position',[.91 .11 .0375 .815]);
    linkaxes([ax1,ax2]) % same positions in 1st and 2nd plot
    

    Result:

    result