MATLAB - Plot a 3D Contour
MATLAB - Modern 3D Contour and Surface Plotting
Section titled “MATLAB - Modern 3D Contour and Surface Plotting”Visualizing three-dimensional data is essential in science and engineering. A 3D contour plot displays isolines (lines of constant value) of a function z = f(x, y) in 3D space. A surface plot renders the entire surface, often colored by height. MATLAB provides a powerful suite of functions for creating these visualizations.
This tutorial covers modern techniques for creating 3D contour and surface plots, focusing on the contour3 and surfc functions, as well as modern object-oriented customization and function-based plotting.
Method 1: 3D Contour Plots with contour3
Section titled “Method 1: 3D Contour Plots with contour3”The contour3 function creates a 3D contour plot, showing the contour lines of a surface at different levels (heights).
Core Syntax
Section titled “Core Syntax”contour3(Z)contour3(X, Y, Z)contour3(..., levels)contour3(..., LineSpec)c = contour3(...) % Get contour object for customizationWhere X, Y, and Z are matrices defining a grid and the height on that grid, typically created with meshgrid.
Example 1: Basic 3D Contour Plot
Section titled “Example 1: Basic 3D Contour Plot”First, we create a 2D grid of (X, Y) coordinates and compute a function Z on this grid. Then we plot the contours of Z.
% 1. Create the data grid[X, Y] = meshgrid(-2:0.25:2, -2:0.25:2);Z = X .* exp(-X.^2 - Y.^2);
% 2. Create the 3D contour plotfigure; % Create a new figure windowcontour3(X, Y, Z, 20); % Plot with 20 contour levels
% 3. Annotate the plottitle('3D Contour Plot of Z = X*exp(-X^2 - Y^2)');xlabel('X-axis');ylabel('Y-axis');zlabel('Z-axis');grid on;This code will produce a figure containing a 3D plot. You will see 20 contour lines, each representing a constant Z-value, floating in 3D space. The lines will trace the shape of the underlying surface, which has a peak and a trough.
Example 2: Advanced Customization
Section titled “Example 2: Advanced Customization”A key modern practice in MATLAB is to get the handle to the plot object to modify its properties after creation. This provides fine-grained control.
[X, Y] = meshgrid(-2:0.25:2, -2:0.25:2);Z = X .* exp(-X.^2 - Y.^2);
figure;
% Specify specific contour levels and capture the object handlelevels = [-0.4, -0.2, 0, 0.2, 0.4];c_handle = contour3(X, Y, Z, levels);
% --- Customize using the object handle ---c_handle.LineWidth = 2; % Make lines thickerc_handle.LineStyle = '--'; % Use dashed linesc_handle.ShowText = 'on'; % Display level values on the contours
title('Customized 3D Contour Plot');xlabel('X-axis');ylabel('Y-axis');view(-15, 25); % Adjust viewing angleThe resulting plot will show only five dashed, thick contour lines at the specified Z-levels. Each line will be labeled with its corresponding value (e.g., ‘0.2’). The view is tilted to provide a better perspective.
Method 2: Surface with Contours using surfc
Section titled “Method 2: Surface with Contours using surfc”The surfc function is powerful because it combines a colored surface plot (surf) with a contour plot beneath it on the xy-plane. This gives a comprehensive view of the data.
Syntax and Example
Section titled “Syntax and Example”surfc(X, Y, Z)s = surfc(...) % Get surface object for customizationLet’s use the standard peaks function, a common benchmark for 3D plotting.
% 1. Generate data using the built-in 'peaks' function[X, Y, Z] = peaks(25);
% 2. Create the combined surface and contour plotfigure;surfc(X, Y, Z);
% 3. Customize and annotatetitle('Surface Plot with Contours for the Peaks Function');xlabel('X');ylabel('Y');zlabel('Z');
% Change the colormap for better visualizationcolormap('jet');colorbar; % Show the color scaleThis script generates a window with a 3D surface plot. The surface’s color corresponds to its height, as indicated by the color bar on the side. Below the 3D surface, on the ‘floor’ of the plot (the xy-plane), you will see the corresponding 2D contour lines.
Advanced Customization with surfc
Section titled “Advanced Customization with surfc”surfc actually returns two objects: one for the surface and one for the contours. We can capture and modify them individually.
[X, Y, Z] = peaks(25);figure;
% Capture the handles for both plot objects[s_handle, c_handle] = surfc(X, Y, Z);
% Customize the surfaces_handle.EdgeColor = 'none'; % Remove the black mesh lines for a smoother looks_handle.FaceAlpha = 0.8; % Make the surface semi-transparent
% Customize the contoursc_handle.LineWidth = 1.5;
title('Customized Surface and Contour Plot');colormap('cool');The output is a more refined visualization. The 3D surface appears smooth and slightly transparent, without the default black grid lines. The contour lines below it are slightly thicker, making them more prominent.
Modern Alternative: Plotting Functions Directly
Section titled “Modern Alternative: Plotting Functions Directly”For mathematical functions, you can often skip the meshgrid step by using fcontour and fsurf. MATLAB will automatically evaluate the function over a suitable range.
figure;
% Define the function as an anonymous functionfun = @(x,y) x .* exp(-x.^2 - y.^2);
% Plot the surface and contour directlyfsurf(fun, [-2, 2]); % The range [-2, 2] applies to both x and yhold on;fcontour(fun, [-2, 2], 'ZLocation', -0.5, 'LineWidth', 2); % Plot contours at z = -0.5hold off;
title('Direct Function Plotting with fsurf and fcontour');This approach is cleaner and more declarative when your data comes from a known mathematical expression.
Mini-Project Idea
Section titled “Mini-Project Idea”Task: Visualize the magnetic field strength around a wire. The field strength B around a long straight wire at the origin follows the formula B(x,y) = k / sqrt(x^2 + y^2), where k is a constant.
- Define a grid for
xandy, avoiding the origin (e.g., use a small offset) to prevent division by zero. - Calculate
Bfor each point on the grid. - Use
surfcto create a surface plot showing how the field strength drops off with distance. - Customize the plot with an appropriate colormap (like
'hot') and labels.