Monday, January 27, 2020

Three-Dimensional Plots

While matplotlib is primarily a 2D plotting package, it does have basic 3D plotting capabilities. To create a 3D plot, we need to import Axes3D from mpl_toolkits.mplot3d and then set the keyword projection to '3d' in a subplot call as shown below:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Different 2D and 3D subplots can be mixed within the same figure window by setting projection='3d' only in those subplots where 3D plotting is desired. Alternatively, all the subplots in a figure can be set to be 3D plots using the subplots function:

fig, ax = plt.subplots(subplot_kw={'projection': '3d'})

As you might expect, the third axis in a 3D plot is called the z-axis, and the same commands for labeling and setting the limits that work for the x and y axes also work for the z-axis.


The following program shows a wireframe and a surface plot of equation shown below:



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


def pmgauss(x, y):
    r1 = (x - 1) ** 2 + (y - 2) ** 2
    r2 = (x - 3) ** 2 + (y - 1) ** 2
    return 2 * np.exp(-0.5 * r1) - 3 * np.exp(-2 * r2)


a, b = 4, 3

x = np.linspace(0, a, 60)
y = np.linspace(0, b, 45)

X, Y = np.meshgrid(x, y)
Z = pmgauss(X, Y)

fig, ax = plt.subplots(1, 2, figsize=(9.2, 4),
                       subplot_kw={'projection': '3d'})
for i in range(2):
    ax[i].set_zlim(-3, 2)
    ax[i].xaxis.set_ticks(range(a + 1))  # manually set ticks
    ax[i].yaxis.set_ticks(range(b + 1))
    ax[i].set_xlabel(r'$x$')
    ax[i].set_ylabel(r'$y$')
    ax[i].set_zlabel(r'$f(x,y)$')
    ax[i].view_init(40, -30)

# Plot wireframe and surface plots.
fig.subplots_adjust(left=0.04, bottom=0.04, right=0.96,
                    top=0.96, wspace=0.05)
p0 = ax[0].plot_wireframe(X, Y, Z, rcount=40, ccount=40,
                          color='C1')
p1 = ax[1].plot_surface(X, Y, Z, rcount=50, ccount=50,
                        color='C1')
fig.subplots_adjust(left=0.0)
fig.savefig('./figures/wireframeSurfacePlots.pdf')
plt.show()

The resulting plot will be as follows:

The 3D wireframe and surface plots use the same meshgrid function to set up the x-y 2D arrays. The rcount and ccount keywords set the maximum number of rows and columns used to sample the input
data to generate the graph.

These plotting examples are just a sample of many kinds of plots that can be made by matplotlib. You need to explore further possibilities.



Share:

0 comments:

Post a Comment