MATLAB: How to create a colorbar that only uses a portion of the colormap in MATLAB 7.0 (R14)

axesclimcolorbarcolormapfigureMATLABsubplot

I have two subplots in a figure and would like to generate a colorbar for each of them. However, they use different portions of the color map, and my two colorbars each show the entire map. I would like to have each colorbar show only the portion of the colormap associated with the subplot.

Best Answer

The colorbar object is a specialized form of the axes object. As such, it has the same properties as any axes objects, including limits on how much of the axes are shown. The following example code generates two surface plots, assigns them to different parts of the colormap, makes two separate colorbars, and restricts the Y axis on each colorbar as necessary.
%set up data, make two plots
ah(1) = subplot(2,1,1)
[x, y, z] = peaks;
s(1) = surf(x,y,z);
ah(2) = subplot(2,1,2)
z2 = z + max(z(:));
s(2) = surf(x,y,z2);
%set the colormap limits for the axes
set(ah,'CLim', [min(z(:)) max(z2(:))])
%make colorbars
subplot(2,1,1)
cbar(1) = colorbar;
subplot(2,1,2)
cbar(2) = colorbar;
%restrict colorbar axes limits
set(cbar(1),'YLim',[min(z(:)) max(z(:))]);
set(cbar(2),'YLim',[min(z2(:)) max(z2(:))]);
The labels displayed next to the colorbars can be changed by setting the "YTickLabel" property, in the same manner as the "YLim" property.