Skip to content

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.

The contour3 function creates a 3D contour plot, showing the contour lines of a surface at different levels (heights).

contour3(Z)
contour3(X, Y, Z)
contour3(..., levels)
contour3(..., LineSpec)
c = contour3(...) % Get contour object for customization

Where X, Y, and Z are matrices defining a grid and the height on that grid, typically created with meshgrid.

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 plot
figure; % Create a new figure window
contour3(X, Y, Z, 20); % Plot with 20 contour levels
% 3. Annotate the plot
title('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.

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 handle
levels = [-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 thicker
c_handle.LineStyle = '--'; % Use dashed lines
c_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 angle

The 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.

surfc(X, Y, Z)
s = surfc(...) % Get surface object for customization

Let’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 plot
figure;
surfc(X, Y, Z);
% 3. Customize and annotate
title('Surface Plot with Contours for the Peaks Function');
xlabel('X');
ylabel('Y');
zlabel('Z');
% Change the colormap for better visualization
colormap('jet');
colorbar; % Show the color scale

This 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.

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 surface
s_handle.EdgeColor = 'none'; % Remove the black mesh lines for a smoother look
s_handle.FaceAlpha = 0.8; % Make the surface semi-transparent
% Customize the contours
c_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 function
fun = @(x,y) x .* exp(-x.^2 - y.^2);
% Plot the surface and contour directly
fsurf(fun, [-2, 2]); % The range [-2, 2] applies to both x and y
hold on;
fcontour(fun, [-2, 2], 'ZLocation', -0.5, 'LineWidth', 2); % Plot contours at z = -0.5
hold 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.

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.

  1. Define a grid for x and y, avoiding the origin (e.g., use a small offset) to prevent division by zero.
  2. Calculate B for each point on the grid.
  3. Use surfc to create a surface plot showing how the field strength drops off with distance.
  4. Customize the plot with an appropriate colormap (like 'hot') and labels.