14. Surfaces in 3D#

Now that we’re familiar with 1D plots, it’s time to move on to 3D visualizations!

Summary of commands#

In this exercise, we will demonstrate the following:

We will plot the function

\[ z(x,y) = \dfrac{\sin(x^2 + y^2)}{x^2 + y^2 + 10^{-16}} \]

for \(x\) ranging between \(-3\) and \(3\), and \(y\) ranging between \(-4\) and \(4\). Use an increment of \(0.1\) in both directions. Include labels and a title, and add a color bar to the figure.

Note

The \(10^{-16}\) in the denominator is needed to avoid division by zero when \(x = y = 0\). Some sources may write this as \(\varepsilon\) (Greek letter epsilon) to represent a tiny quantity.

import numpy as np
import matplotlib.pyplot as plt

# values
x = np.arange(-3, 3, 0.1)
y = np.arange(-4, 4, 0.1)
X, Y = np.meshgrid(x, y)
print(X.shape)
Z = np.sin(X**2 + Y**2) / (X**2 + Y**2 + 1e-16)

fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(projection='3d')
surf = ax.plot_surface(X, Y, Z, cmap='viridis', antialiased=False)
fig.colorbar(surf, pad=0.15, shrink=0.7)
ax.set(xlabel='x', ylabel='y', zlabel='z', title='Nice 3D plot')
plt.show()
(80, 60)
../_images/625d73ffe7ae83bff587f217ee944b3d4b22c745c9bcad95b840e35aa2370077.png

Several things to note#

Meshgrid#

  • Look at the shape of \(X\) (or \(Y\), \(Z\)): It is two dimensional, and if you look the values, it essentially repeats every value of \(x\) at every value of \(y\) (and vice versa).

  • A lesson in descriptive variable names: In math, we are used to using lowercase letters for scalars/vectors, and uppercase letters for matrices. So we do the same here!

Surface plot#

  • We used the cmap parameter when making the surface plot to choose an appropriate colormap. Otherwise the whole plot is a default blue and less helpful.

  • We also added antialiased=False which is somewhat similar to shading('interp') that you might be used to seeing in MATLAB.

  • We did not modify the rstride and cstride parameters, but you could to make the rendering finer (e.g., set both to 1).

Other#

  • We had to tweak the color bar a little bit to make it fit better. See the documentation for more details.

  • We might not get the nice click-and-drag features of MATLAB plots in Colab (there are other interactive plotting libraries), but if you wanted to change the viewing angle, you can explore ax.view_init(elev, azim, roll).