MATLAB: How to set the colorbar to have a limited number of colors

colormapdwhhgMATLAB

When I execute the command COLORBAR, I receive a colorbar with a full range of 64 colors. I would like the colorbar to reflect only the limited number of colors present in my contour plot.

Best Answer

For MATLAB versions R2014b and later:
As of MATLAB R2014b, you can accomplish this with the 'colormap' function. You can use the 'colormap' function to customize the range of colors that gets displayed. You can create a completely custom colormap by specifying each RGB value:
map = [0, 0, 0.3;
0, 0, 0.4;
0, 0, 0.5;
0, 0, 0.6;
0, 0, 0.8;
0, 0, 1.0];
colormap(map)
Or if you would like a starting point for creating the values in 'map', you can use values from one of the built-in colormaps:
>> map = parula(64)
For MATLAB versions R2014a and earlier:
The ability to set the number of colors in a colorbar is not directly available in MATLAB.
However, this is possible by changing the 'CData' property of the image that resides in the COLORBAR axes, as shown in the example below:
mx = peaks(100);
numberOfColors = 5;
% This value will be used in the code below to set the number of colors as desired
nc = numberOfColors-1;
% Use this syntax of contourf to select number of contours
[c,h, cf] =contourf(mx,nc);
cb = colorbar;
% Find the image inside the colorbar object,
% then find the limits of the data to set colorbar axes
i = findobj(cb,'type','image');
minVal = min(mx(:));
maxVal = max(mx(:));
% Set the colorbar's CData to the desired number of intervals
set(i,'cdata',[0:64/nc:64]','YData',[minVal maxVal]);
Finally, set the tick marks of the colorbar:
% Option 1: Set the colorbar ticks to sit in the center of the color bins
set(cb,'yLim',[minVal maxVal],'ytick',[minVal:(maxVal-minVal)/(nc):maxVal]');
% Option 2: Set the ticks to sit both at the centers and at the edges of the color bins
%set(cb,'yLim',[minVal maxVal],'ytick',[minVal:(maxVal-minVal)/(2*nc):maxVal]');
You can refer to the documentation for more details and examples: