Tuesday, September 27, 2016

Python: Matplotlib: 3D Plot Example

Noteworthy:

# "Creates a new figure."
matplotlib.pyplot.figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=<class 'matplotlib.figure.Figure'>, **kwargs)

# "Renders into a FigureCanvas."
class matplotlib.figure.Figure(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)

# "Get the current Axes instance on the current figure matching the given keyword args, or create one."
matplotlib.pyplot.gca(**kwargs)

# "Return evenly spaced values within a given interval."
numpy.arange([start, ]stop, [step, ]dtype=None)

# "Return coordinate matrices from coordinate vectors."
numpy.meshgrid(*xi, **kwargs)

# "Return the positive square-root of an array, element-wise."
numpy.sqrt(x[, out]) = <ufunc 'sqrt'>

# "Trigonometric sine, element-wise."
numpy.sin(x[, out]) = <ufunc 'sin'>

# "Create a surface plot."
Axes3D.plot_surface(X, Y, Z, *args, **kwargs)


Command:

$ cat test3dplot.py


Result:

#!/usr/local/bin/python

from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

plt.style.use('dark_background')
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm)
plt.show()


Command:

$ python test3dplot.py

Graphical output: