MATLAB: How to change the contour line colors for specific elevations using CONTOUR

colorcontourelevationlevellineMATLABplot

I have plotted a graph using CONTOUR. I would like to be able to specify the contour line color based on elevation.

Best Answer

For R2014b and newer versions:
The following link describes how to highlight specific contour levels:
The link shows how to change 'LineWidth' based on the elevation level. You can also change the 'EdgeColor' property here to get the desired effect.
For versions prior to R2014b:
MATLAB uses a system of graphics objects (Handle Graphics) to implement graphing and visualization functions. Each object created has a fixed set of properties. You can use these properties to control the behavior and appearance of your graph.
When you create a contour plot using the following syntax, you gain access to the associated contourgroup object handle 'h'. This contourgroup object has patch objects as children. These patch objects are used to display the contour lines associated with the various elevations.
[C,h] = contour(...)
In order to specify the contour line colors based on the elevation they represent, you have to manipulate the 'EdgeColor' property of the patch object for a given elevation. To find what elevation a given patch object is associated, check the 'UserData' property associated with the patch object.
The following code snippet demonstrates how to change line colors for the contour plotted in example 1 in the documentation for CONTOUR. The contour line at elevation 0.4 is set to display as a blue line, whereas the contour line at elevation -0.4 will display a red line.
[X,Y]=meshgrid(-2:.2:2,-2:.2:3);
Z=X.*exp(-X.^2-Y.^2);
[C,h]=contour(X,Y,Z);
set(h,'ShowText','on','TextStep',get(h,'LevelStep')*2)
%begin code to change specific line colors
%get a handle to all the children of the contourgroup object
a=get(h,'Children');
%loop through all the children of the contourgroup object
for k=1:length(a)
%only consider the children that are patch objects
%STRCMP compares two strings and return true if they are the same
if strcmp(get(a(k),'Type'),'patch')
%'UserData' indicates the elevation associated with a patch
switch get(a(k),'UserData')
case 0.4
set(a(k),'EdgeColor','b');
%set the 'EdgeColor' for the line at elevation 0.4 to blue
case -0.4
set(a(k),'EdgeColor','r');
%set the 'EdgeColor' for the line at elevation -0.4 to red
end
end
end
For more information regarding the commands used above,please consult the documentation by executing the following at the MATLAB prompt:
doc get
doc set
doc strcmp
doc switch