flawr
flawr

Reputation: 11628

Colorbar limits not respecting axes clims when displaying an image

Im trying to superimpose a trimesh-plot over a image imshow using hold on. This works fine so far. I'd additionally like to display a colorbar, which works too, but unfortunately it does not adjust to the range specified by caxis, does anyone have an idea how to fix this?

This is an example output: The colourbar should display a range from 1 to z, not from 0 to 60. If we remove imshow everything works fine.

Here my MCVE:

clc;clf;clear
T = [1,2,3;3,1,4]; % triangulation
X = [0,1,1,0]*300; % grid coordinates
Y = [0,0,1,1]*300;
for z = 2:20;
    clf;
    imshow(imread('board.tif')) % plot image (this is a built in matlab test image)
    hold on
    Z = [1,1,1,z];
    trisurf(T,X,Y,Z)            % superimpose plot 
    colormap hot
    caxis([1,z])
    colorbar
    drawnow
    pause(0.5)
end

Upvotes: 3

Views: 193

Answers (1)

Suever
Suever

Reputation: 65460

This appears to be a bug in how older versions of MATLAB handled the colorbar (it's not present with HG2). The "correct" behavior would be that if you have any objects in the current axes that use scaled values, then the colorbar should respect your clims. It seems that MATLAB is using the first child in the current axes to determine whether to respect your clims or not. imshow does not use scaled CDataMapping so colorbar simply ignores your clims.

It looks like you have three options:

  1. Use imagesc rather than imshow

    clf;
    imagesc(imread('board.tif'));
    axis image
    hold on
    Z = [1,1,1,z];
    trisurf(T,X,Y,Z)            % superimpose plot
    colormap hot
    caxis([1,z])
    drawnow
    colorbar
    drawnow
    pause(0.5)
    
  2. Call imshow after you've created your trisurf object

    clf;
    hold on
    Z = [1,1,1,z];
    trisurf(T,X,Y,Z)            % superimpose plot
    colormap hot
    him = imshow(imread('board.tif'));
    caxis([1,z])
    drawnow
    colorbar
    drawnow
    pause(0.5)
    
  3. Set the CDataMapping property of the image object to 'scaled' (will be ignored when displaying the image since it's RGB but it will allow the colorbar to function properly)

    clf;
    him = imshow(imread('board.tif'));
    set(him, 'CDataMapping', 'scaled')
    hold on
    Z = [1,1,1,z];
    trisurf(T,X,Y,Z)            % superimpose plot
    colormap hot
    caxis([1,z])
    drawnow
    colorbar
    drawnow
    pause(0.5)
    

Upvotes: 2

Related Questions