Kahibaro
Discord Login Register

3D Plots and Surface Plots

Understanding 3D Plotting in MATLAB

3D plotting in MATLAB extends the ideas of simple 2D plotting into an extra dimension. Instead of visualizing a relationship between two variables, you can display how a value changes over two independent variables, or visualize collections of points in three dimensional space. MATLAB provides several basic 3D plotting functions, with plot3, mesh, and surf being the most common starting points for beginners.

A 3D plot uses three coordinate axes, usually labeled $x$, $y$, and $z$. In MATLAB, the simplest way to think about this is that you always need three coordinates for each point you want to draw. For surface plots, you usually think of $z$ as a function of $x$ and $y$, written as $z = f(x,y)$, and MATLAB helps you construct a grid of $(x,y)$ points and the corresponding $z$ values.

Using plot3 for 3D Line Plots

The function plot3 is the 3D counterpart to the basic plot function. Instead of giving x and y vectors, you pass x, y, and z vectors of the same length. MATLAB then draws a line or multiple lines in 3D space according to those coordinates.

At its simplest, the syntax looks like this.

t = linspace(0, 10, 200);           % parameter
x = cos(t);
y = sin(t);
z = t;
plot3(x, y, z)
grid on
xlabel('x')
ylabel('y')
zlabel('z')
title('Simple 3D Helix using plot3')

In this example, the vectors x, y, and z define a helix. The grid on command is often very helpful in 3D, because it gives you a reference for the axes that makes depth easier to judge.

You can customize plot3 in a similar way to plot. You can pass a line specification string to control color, marker, and line style, or set properties after plotting.

plot3(x, y, z, 'r--', 'LineWidth', 2)

Here, 'r--' selects a red dashed line, and 'LineWidth', 2 makes the line thicker. Just like with 2D plots, you can call hold on to draw several 3D lines in the same axes.

When working with 3D plots, rotation is especially important. You can click and drag in the figure window to rotate the view interactively. MATLAB stores the viewing angle internally, and you can also control it with the view function, for example view(az, el) where az is azimuth and el is elevation in degrees.

Creating Grids with meshgrid

Surface plots such as mesh and surf usually work with a grid of points in the $x$ and $y$ directions, and a matrix of corresponding $z$ values. You do not usually specify each $(x,y,z)$ point individually. Instead, you start by creating vectors of $x$ and $y$ coordinates and then expand them into 2D grids.

The function meshgrid is the standard way to do this in MATLAB. Given vectors x and y, it creates two 2D arrays X and Y that contain all combinations of these coordinates.

x = -2:0.1:2;
y = -2:0.1:2;
[X, Y] = meshgrid(x, y);
Z = X.^2 + Y.^2;

In this example, the vectors x and y have individual coordinate values. The matrices X and Y contain repeated rows and columns so that X(i,j) and Y(i,j) give the $x$ and $y$ coordinates of one point on a rectangular grid. The matrix Z must be the same size as X and Y, and you often compute it using elementwise operations. Here, the height is $z = x^2 + y^2$ at each grid point.

It is important to pay attention to elementwise operators such as .^ and .* when computing Z. Those operators ensure that the function is evaluated at each element of X and Y.

mesh: Wireframe Surface Plots

The function mesh draws a wireframe surface by connecting grid points with lines in the $x$ and $y$ directions. It does not fill the surface with solid color, so it can be useful when you want to see through the surface or understand the grid structure.

Using the previously defined X, Y, and Z, you can create a simple mesh plot like this.

mesh(X, Y, Z)
xlabel('x')
ylabel('y')
zlabel('z')
title('Paraboloid: z = x^2 + y^2')

By default, mesh colors the lines according to the current colormap and the height values. The coloring follows the matrix Z, so higher or lower regions can be distinguished by color as well as by position.

You can switch to a simpler coloring that uses a single color by changing properties. One approach is to disable the color mapping based on Z.

h = mesh(X, Y, Z);
h.EdgeColor = 'k';      % black edges
h.FaceColor = 'none';   % keep it as a wireframe

This treats the mesh as a graphics object and sets its properties. Learning to adjust object properties is part of handle graphics and is introduced separately, but here you only need to see that mesh returns a handle you can modify.

The mesh resolution depends on how finely you sample the x and y vectors. More points produce smoother looking surfaces but require more computation and can make rotation less responsive on slower machines. You can experiment by changing the step sizes in x and y.

surf: Colored Surface Plots

The function surf draws a filled surface instead of a wireframe. Each small rectangular patch on the surface can be colored according to the corresponding Z value. This helps you see variations in the surface height with color as well as shape.

Continuing with the same grid, you can create a surface plot as follows.

surf(X, Y, Z)
xlabel('x')
ylabel('y')
zlabel('z')
title('Surface Plot: z = x^2 + y^2')
colorbar

The colorbar function adds a bar that shows how numerical values of Z map to colors. This is important when you want to interpret colors quantitatively.

By default, surf both draws the surface and outlines each patch. This can look a bit busy. You can smoother the appearance by removing the edges and adjusting shading.

surf(X, Y, Z)
shading interp       % smooth color interpolation
xlabel('x')
ylabel('y')
zlabel('z')
colorbar

The command shading interp interpolates colors across patches and removes the black grid lines. Another option is shading flat, which keeps solid color per patch, and shading faceted, which is the default.

You can also control the colormap, which is the set of colors used to represent different Z values. For instance, colormap parula or colormap jet changes the appearance of the surface. The choice of colormap is mostly visual, but some colormaps are better suited to displaying data clearly.

Controlling the View and Axis in 3D

Once you have a 3D plot, such as a mesh or surf plot, the viewing angle becomes very important. MATLAB lets you rotate the view interactively, but you can also set a specific view using the view function. The common form is view(az, el), where az is the azimuth, the rotation around the vertical axis, and el is the elevation, the angle above or below the horizontal plane.

For example, to use a top view that looks straight down on the $x$ $y$ plane, you can use view(2). To use a default 3D view, you might try something like view(45, 30).

surf(X, Y, Z)
axis tight
view(45, 30)

The axis command also works with 3D plots. axis equal makes the units along each axis equal in length, which prevents distortion of geometric shapes. axis tight adjusts the axis limits to fit the data bounds closely.

The function zlim controls the vertical axis limits separately, similar to xlim and ylim for the horizontal axes. This can be useful when you want to focus on a specific range of heights.

zlim([0 3])

Combining these commands lets you refine how the 3D plot appears and how easy it is to interpret.

Visualizing Common 3D Surfaces

Surface plots become clearer when you see some typical mathematical examples. One standard test surface in MATLAB is the peaks function. You can call peaks without arguments to get a sample surface, or specify a grid size.

Z = peaks(50);
surf(Z)
shading interp
colormap parula
colorbar
title('Sample Surface using peaks')

Here surf(Z) assumes default X and Y coordinates that range over a square grid, which is often good enough for demonstration. The peaks function creates a surface with multiple hills and valleys, which is a good example for testing colormaps and lighting.

You can also use your own function definitions. For instance, to plot $z = \sin(r)$ where $r = \sqrt{x^2 + y^2}$, you can create a grid and evaluate it.

x = linspace(-4, 4, 100);
y = linspace(-4, 4, 100);
[X, Y] = meshgrid(x, y);
R = sqrt(X.^2 + Y.^2);
Z = sin(R) ./ (R + eps);     % avoid division by zero at the center
surf(X, Y, Z)
shading interp
colormap turbo
colorbar
title('Damped Radial Waves Surface')

The eps term is a small value that prevents division by zero at $r = 0$. This example shows how a relatively simple formula can produce an intricate 3D surface.

Combining mesh and surf with contour

Sometimes it is useful to combine 3D surfaces with contour information. Although full contour plotting is a separate topic, it is common to overlay contours on a surface or show them projected onto a plane.

You can use hold on to combine a surf plot with contour lines at the bottom of the plot.

surf(X, Y, Z)
shading interp
hold on
contour3(X, Y, Z, 20, 'k')   % 20 contour levels, black lines
hold off

The function contour3 draws contour lines in 3D, which can help emphasize certain $z$ levels. Even if you do not use contour3 in detail yet, it is helpful to see that 3D plots can be combined with other graphics commands in familiar ways.

Working with 3D Scatter and Points

While plot3 draws lines through 3D points, the scatter3 function is designed for plotting separate points with symbols in 3D. It corresponds to scatter in 2D. This can be useful for visualizing data that consist of point clouds, such as measured coordinates or simulation results.

The basic syntax for scatter3 is similar to plot3, but it also accepts size and color information for each point.

x = randn(200,1);
y = randn(200,1);
z = x.^2 - y.^2;
scatter3(x, y, z, 36, z, 'filled')
xlabel('x')
ylabel('y')
zlabel('z')
colorbar
title('3D Scatter Plot with Color Mapping')

In this example, the fourth argument 36 sets the marker size, and the fifth argument z sets the color of each point according to its height. The 'filled' option fills the markers rather than drawing just their edges.

Although scatter plots are not surfaces in the strict sense, they are part of basic 3D visualization and use similar controls for view, axes, and colormaps.

Simple Lighting and Shading Effects

Surface plots can often benefit from basic lighting, which gives a more three dimensional appearance. MATLAB provides simple commands such as light, lighting, and material to control this. Even without going deeply into graphics, you can try a few simple combinations.

For example, after creating a surface with surf, you can add a light source and change lighting to a smoother phong model.

surf(X, Y, Z)
shading interp
colormap parula
camlight headlight
lighting phong

The command camlight headlight creates a light that moves with the camera, so as you rotate the view the lighting stays consistent. The lighting phong setting produces smooth shading across the surface. You can experiment with lighting gouraud or lighting flat to see different effects.

Lighting is especially helpful when color does not change much across the surface, because highlights and shadows help you see shape better.

Exporting 3D Plots for Use Elsewhere

3D figures can be saved and exported in almost the same way as 2D figures. You can use the figure window menus, or commands such as saveas and exportgraphics. For example, to save the current figure as a PNG image, you can call

exportgraphics(gcf, 'my3Dplot.png', 'Resolution', 300)

Here gcf refers to the current figure. Higher resolutions are more suitable for printing or high quality reports. The details of exporting figures are discussed separately, but it is helpful to know that 3D plots do not require any special treatment for basic exporting.

Important points to remember:
3D line plots use plot3(x, y, z) with vectors of equal length.
Surface plots usually start with meshgrid to create X and Y, and a matching Z matrix.
Use mesh for wireframe surfaces and surf for filled, colored surfaces.
Always use elementwise operators like .^ and .* when computing Z from X and Y.
Control the view with view, and adjust axes with axis, xlim, ylim, and zlim.
Colormaps and colorbar help interpret height values in surface plots.
You can rotate 3D figures interactively by dragging with the mouse.

Views: 3

Comments

Please login to add a comment.

Don't have an account? Register now!