Plot3D in Mathematica, a Worked Example
Turn a function of two variables into a surface you can color, rotate and read.
Plot3D[f[x, y], {x, -4, 4}, {y, -4, 4}]f[x_, y_] := Sin[x] Cos[y] Exp[-(x^2 + y^2)/10]
Four things to keep in mind about Plot3D.
Plot3D takes a function of two variables and one range for each: {x, xmin, xmax} and {y, ymin, ymax}.
Define the function once with := and plot it by name, so every plot draws the same surface.
Options go after the ranges, written Name -> value. They change how the surface looks, never the function.
Mesh, colors and lighting are all options: the default orange surface is only a starting point.
Plot3D[f[x, y], {x, -4, 4}, {y, -4, 4}] draws an orange surface with a grid of mesh lines. The sampling, the colors and the lighting are all automatic.ColorFunction colors each point by its height; in the function you give it, #3 stands for z. Here the colors run from navy in the valleys to coral on the peaks, with Mesh -> None to drop the grid and PlotPoints -> 50 for a smoother surface.MeshFunctions -> {#3 &} with Mesh -> 12 replaces the grid with 12 lines of constant height, the way a topographic map marks elevation.Show[surface, floor] puts the two together. Each ring on the floor lies directly under the hill or valley it describes. The FAQ below has the code.
It draws the surface z = f(x, y) for a function of two variables over a rectangle of x and y values. The basic form is Plot3D[f[x, y], {x, xmin, xmax}, {y, ymin, ymax}].
Raise PlotPoints, the number of sample points in each direction (try 50 to 100), and MaxRecursion, how many times Mathematica may subdivide where the surface bends. Sharp peaks and narrow valleys gain the most.
Add AxesLabel -> {"x", "y", "z"} for the axes and PlotLabel -> "My surface" for a title.
Draw the surface and a flat plane below it, color and mesh the plane by the same function, and combine them with Show:surface = Plot3D[f[x, y], {x, -4, 4}, {y, -4, 4}, MeshFunctions -> {#3 &}, Mesh -> 12];floor = Plot3D[-1.5, {x, -4, 4}, {y, -4, 4}, MeshFunctions -> {f[#1, #2] &}, Mesh -> 12, ColorFunction -> Function[{x, y, z}, ColorData["SunsetColors"][(f[x, y] + 0.82)/1.64]], ColorFunctionScaling -> False];Show[surface, floor, PlotRange -> {-1.5, 1}]
The 0.82 and 1.64 rescale the function, which runs from about −0.81 to 0.81, onto the 0-to-1 range a color scheme expects.
Plot3D draws one height z above each point (x, y), so its surface never folds over itself. ParametricPlot3D gives x, y and z each as a function of two parameters, so it can draw spheres, tori and surfaces that curl back on themselves.
Our Mathematica Essentials course starts with your first notebook and covers functions, lists, 2D and 3D graphics, solving equations, derivatives and integrals, and working with data, in short video lessons with quizzes.