Surface Plots

This is a lightly edited version of surface3D_demo.py from https://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html

This notebook demonstrates plotting a 3D surface colored with the coolwarm color map. The surface is made opaque by using antialiased=False. It also demonstrates using the LinearLocator and custom formatting for the z axis tick labels.

Marty Ligare, August 2020

In [3]:
import numpy as np
import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
In [4]:
%matplotlib notebook

Sample function $f(x,y)$

$$ f(x,y) = -\exp\left[ -(x-1)^2 - \frac{y^2}{2^2} \right] - \frac{3}{2}\exp\left[-\frac{x^2}{1/2^2} - \frac{(y+2)^2}{2^2}\right] $$
In [5]:
def f(x,y):
    return -np.exp(-(x-1)**2 - y**2/2**2) - 1.5*np.exp(-x**2/0.5**2 - (y+2)**2/2**2)
In [6]:
fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
x = np.linspace(-1, 2, 201)
y = np.linspace(-4, 1, 201)
X, Y = np.meshgrid(x, y, indexing='ij')
Z = f(X,Y)

# OR
Z = np.zeros((len(x), len(y)))
for i in range(len(x)):
    for j in range(len(y)):
        Z[i,j] = f(x[i], y[j])

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)

# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

plt.xlabel('$x$')
plt.ylabel('$y$')
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5);

Contour plot

In [7]:
plt.figure()
CS = plt.contour(X, Y, Z)
#CS = plt.contour(X, Y, Z, levels=[-1.5,-1.3,-1.1,-0.9,-0.7,-0.5])
plt.clabel(CS, inline=1, fontsize=10)
plt.xlabel('$x$')
plt.ylabel('$y$');

Version information

  • %version_information is an IPython magic extension for showing version information for dependency modules in a notebook;

  • See https://github.com/jrjohansson/version_information

  • %version_information is available on Bucknell computers on the linux network. You can easily install it on any computer.

In [8]:
%load_ext version_information
In [9]:
version_information numpy, scipy, matplotlib
Out[9]:
SoftwareVersion
Python3.7.7 64bit [GCC 7.3.0]
IPython7.16.1
OSLinux 3.10.0 1062.9.1.el7.x86_64 x86_64 with centos 7.7.1908 Core
numpy1.18.5
scipy1.5.2
matplotlib3.3.0
Wed Aug 05 20:37:58 2020 EDT
In [ ]: