Home > Software engineering >  How do I plot the gradient calculated from a multivariable function?
How do I plot the gradient calculated from a multivariable function?

Time:10-23

Let's say I have following python code:

import numpy as np
import matplotlib.pyplot as plt

fig=plt.figure()
ax=plt.axes(projection='3d')
x=y=np.linspace(1,10,100)
X,Y=np.meshgrid(x,y)
Z=np.sin(X)**3 np.cos(Y)**3
ax.plot_surface(X,Y,Z)
plt.show()

How do I calculate from this code the gradient and plot it? I am also confused in what numpy.gradient() function exaclty returns.

I have here the graph of the function. enter image description here

CodePudding user response:

gradient is a vector. It has 2 components (in this case, since we are dealing with function ℝ²→ℝ, X,Y↦Z(X,Y)), one which is ∂Z/∂X, (also a function of X and Y), another which is ∂Z/∂Y.

So, np.gradients returns both. np.gradient(Z), called with a 100×100 array of Z, returns a list [∂Z/∂X, ∂Z/∂Y], both being also 100×100 arrays of values: a 100×100 arrays of ∂Z/∂X values, and a 100×100 arrays of ∂Z/∂Y values.

As for how to plot it, it is up to you. How would you like to plot it? You could use the gradient to alter colors, for example. Or draw arrows.

CodePudding user response:

Here is the practical way to achieve it:

import numpy as np
import matplotlib.pyplot as plt

x = y = np.linspace(1, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X)**3   np.cos(Y)**3

# Gradient w/ units:
dZ = np.gradient(Z, x, y)

fig, axe = plt.subplots()
axe.contour(X, Y, Z, 30, cmap="jet")
axe.quiver(X, Y, *dZ)
axe.set_aspect("equal")
axe.grid()

It renders:

enter image description here

There are two visualizations of interest to see the gradient:

  • Quiver which allow you to render the vector field, see plt.quiver to tune arrows;
  • Contour which allow you to render isopleth (levels), see plt.contour to adapt levels.
  • Related