Search code examples
matlabcolorscustomizationcolorbarcolormap

How to control colorbar color ranges in Matlab plots?


I have the following code:

[X,Y,Z] = peaks(30);
crange = 1.5;

[maxval dummy] = max(Z(:));
[minval dummy] = min(Z(:));

% green, yellow, red
cmap = [0 1 0; 1 1 0; 1 0 0];  

figure
colormap(cmap); 
surf(X,Y,Z);
caxis([30 55]);
cbh=colorbar;
set(cbh,'Ytick',[30 32 38 55]);

enter image description here

My goal is to set the limits of the color bar so that the colors are like this:

  • green from 30 to 32
  • yellow from 32 to 38
  • red from 38 to 55

I believe I should somehow change the CData variable, so I used these lines of code without success:

i = findobj(cbh,'type','image');
set(i,'cdata',[30 32 38]','YData',[30 55]);

Solution

  • Your custom colorbar consists of (32-30 = ) 2 + (38-32 = ) 6 + (55-38 = ) 17 = 25 "units" of color. So a simple trick would be replicating each color the required number of "units":

    function q58097577
    [X,Y,Z] = peaks(30); Z = (Z - min(Z(:)))*5;
    
    % green, yellow, red
    nG = 32-30; nY = 38-32; nR = 55-38;
    cmap = [ repmat([0 1 0], [nG 1]); repmat([1 1 0], [nY,1]); repmat([1 0 0], [nR,1]) ];  
    
    figure()
    colormap(cmap); 
    surf(X,Y,Z);
    caxis([30 55]);
    cbh=colorbar;
    set(cbh,'Ytick',[30 32 38 55]);
    

    Resulting in:

    enter image description here