Gradient Fields

We’ll use Mathematica to find gradients, plot gradient fields, and then plot gradient fields with level curves to visually inspect the claim that gradients are perpendicular to level curves.

The general commands for f [x, y] , a function of two variables, are:

Gradient: Grad[f [x, y], {x, y}]

Gradient Field: VectorPlot[ the gradient of f , {x, a, b}, {y, c, d}  ]

Note that VectorPlot is a general command to produce vector fields, and if you wanted something other than the gradient field of f, you’d enter {f_1(x, y), f_2(x, y)} where f_1 and f_2 are any two scalar fields on two variables. It generalizes to vector fields in three dimensions in the way you’d hope.

Level Curves: ContourPlot[ f [x, y], {x, a, b}, {y, c, d}, ContourShading->None ] 
(Note: If we don’t add ‘ContourShading->None’ the contour plot obscures the vector field.)

Name any output: blah = command

Put the two graphs (named p1 and p2) together: Show[ p1, p2 ]



Let’s do an example. First, we plot the graph of the scalar field.

Plot3D[x^2*Sin[y]+y*Sin[x],{x,-6,6},{y,-6,6}]

Next, we find the gradient. Note that I’m naming the output gradient vector field ‘brad’ so that I can simply put ‘brad’ into the next command. There are other ways to do it.

brad =Grad[x^2*Sin[y]+y*Sin[x],{x,y}]

Now, find the gradient field.

p1 =VectorPlot[brad,{x,-6,6},{y,-6,6}]

Let’s find the level curves for the original function f.

p2=ContourPlot[x^2*Sin[y]+y*Sin[x],{x,-6,6},{y,-6,6},ContourShading->None]

Now, put together the contour plot and the gradient field.

Show[p1,p2]

This is a bit of a side venture, but we can also do something similar with the very useful command StreamPlot[ the gradient of f , {x, a, b}, {y, c, d}  ]. This command shows the vector field along with the curves that the vectors are tangent to. Very useful for Differential Equations and Multivariable Calculus.

p3 = StreamPlot[brad,{x,-6,6},{y,-6,6}]

Show[p1,p3]

Here’s a particularly nice rendition of the combination of the gradient field and level curves.

gad =Grad[Sqrt[x^2+y^2],{x,y}]
p4 =VectorPlot[gad,{x,-6,6},{y,-6,6}]
p5 = ContourPlot[Sqrt[x^2+y^2],{x,-6,6},{y,-6,6},ContourShading->None]
Show[p4,p5]

With suitable modifications, this works for three dimensions, too! Here’s the 3-d version of the previous problem.

graduate =Grad[Sqrt[x^2+y^2+z^2],{x,y,z}]
p6 =VectorPlot3D[graduate,{x,-6,6},{y,-6,6}, {z,-6,6}]
p7 = ContourPlot3D[Sqrt[x^2+y^2+z^2],{x,-6,6},{y,-6,6},{z,-6,6}]
Show[p6,p7]

Amazing, isn’t it? Feel free to use these commands when it makes sense.