MATLAB: How to designate color in contour plot with specific values

binaryblack and whitecolormapcontour

How do I color the contour plot black for values of a specific number or higher and lower values will be white?

Best Answer

Here's a demo.
  1. Produce the contour plot.
  2. Set the binaryThreshold variable that defines the border of white/black
  3. Redefine the colormap
% Create contour plot
Z = peaks;
[~,c] = contourf(Z);
cb = colorbar();
% Set binary threshold to separate the two colors.
% See c.LevelList for list of contour levels, although you can
% set this value to any value within the range of levels.
binaryThreshold = 2.0;
% Determine where the binary threshold is within the current colormap
% All changes to contour plot should be made prior to this.
ax = gca();
crng = caxis(ax); % range of color values (same as min|max of c.LevelList)
clrmap = ax.Colormap;
nColor = size(clrmap,1);
binThreshNorm = (binaryThreshold - crng(1)) / (crng(2) - crng(1));
binThreshRow = round(nColor * binThreshNorm); % round() results in approximation
% Change colormap to binary
% White section first to label values less than threshold.
newColormap = [ones(binThreshRow,3); zeros(nColor-binThreshRow, 3)];
ax.Colormap = newColormap;
% Add gray contour line labels
c.LineColor = [.5 .5 .5];
c.LineWidth = 2;
% Add frame to colorbar
cb.LineWidth = .7;
Note that since all colormaps have a discrete number of colors, the border between black & white is very closely approximated and will most likely not cause a problem. For example, with a colormap of 256 colors, if the threshold is set to 33% of the color range, the transition would happen between color #84 and #85 which would be rounded to 84. If this poses a problem, you can either slightly reduce or increaes the threshold or you can change round() to ceil() or floor().