A few months ago I discussed various undocumented manners by which we can customize Matlab contour plots. A short while ago I receive an email from a blog reader (thanks Frank!) alerting me to another interesting way by which we can customize such plots, using the contour handle’s hidden ContourZLevel property. In today’s post I will explain how we can use this property and expand the discussion with some visualization interactivity.
The ContourZLevel property
The contour handle’s ContourZLevel property is a hidden property. This means that, just like all other hidden properties, it is accessible if we just happen to know its name (which is easy using my getundoc utility). This property sets the Z level at which the contour lines are drawn.
For example, by default the meshc function sets ContourZLevel‘s value to the bottom of the 3D display (in other words, to the axes’ ZLim(1) value). This is done within the mesh.m function:
We can, however, modify the contour’s level value to any other Z location:
% create a mesh and contour plot handles = meshc(peaks); % handles is a 2-element array of handles: the surface plot and the contours hContour = handles(2); % get the handle to the contour lines hContour.ContourZLevel = 4.5; % set the contour's Z position (default: hAxes.ZLim(1)=-10) % We can also customize other aspects of the contour lines, for example: hContour.LineWidth = 2; % set the contour lines' width (default: 0.5)
Adding some visualization interactivity
Now let’s add some fun interactivity using a vertical slider to control the contour’s height (Z level). Matlab’s slider uicontrol is really just an ugly scrollbar, so we’ll use a Java JSlider instead:
% Add a controlling slider to the figure jSlider = javaObjectEDT(javax.swing.JSlider); jSlider.setOrientation(jSlider.VERTICAL); jSlider.setPaintTicks(true); jSlider.setMajorTickSpacing(20); jSlider.setMinorTickSpacing(5); jSlider.setBackground(java.awt.Color.white); [hjSlider, hContainer] = javacomponent(jSlider, [10,10,30,120], gcf); % Set the slider's action callback hAxes = hContour.Parent; % handle to containing axes zmin = hAxes.ZLim(1); zmax = hAxes.ZLim(2); zrange = zmax - zmin; cbFunc = @(hSlider,evtData) set(hContour,'ContourZLevel',hSlider.getValue/100*zrange+zmin); hjSlider.StateChangedCallback = cbFunc; % set the callback for slider action events cbFunc(hjSlider,[]); % evaluate the callback to synchronize the initial display