Matplotlib

Chapter 14 – 3D Plotting and Surface Visualization in Matplotlib

Matplotlib isn’t limited to 2D charts — it also supports rich 3D visualizations using the mplot3d toolkit.

In this chapter, you’ll learn how to create 3D line, surface, and scatter plots, visualize data in three dimensions, and adjust camera angles and color maps for stunning effects.

✅ What You’ll Learn

  • Setting up 3D plots using Axes3D
  • Creating 3D line and scatter plots
  • Visualizing surfaces and contours
  • Customizing axes, colors, and view angles
  • Building 3D visualizations for scientific data

✅ 1. Enabling 3D Plotting

To start using 3D plots, you need to import Axes3D from the mpl_toolkits.mplot3d module.


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

✅ 2. Creating a Simple 3D Line Plot

You can create a 3D plot by initializing a figure and adding a 3D subplot.


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.linspace(0, 10, 100)
y = np.sin(x)
z = np.cos(x)

ax.plot3D(x, y, z, 'b', linewidth=2)
ax.set_title('3D Line Plot')
plt.show()

Here:
projection='3d' activates 3D rendering.
ax.plot3D() draws a 3D curve using x, y, and z coordinates.

✅ 3. 3D Scatter Plot

Scatter plots help visualize relationships among three continuous variables.


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)

ax.scatter(x, y, z, c='r', marker='o')
ax.set_title("3D Scatter Plot")
plt.show()

You can control color (c), size (s), and marker shapes just like in 2D scatter plots.

✅ 4. 3D Surface Plot

Surface plots are perfect for visualizing mathematical functions or terrain-like data.


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

X = np.linspace(-5, 5, 100)
Y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(X, Y)
Z = np.sin(np.sqrt(X**2 + Y**2))

ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
ax.set_title('3D Surface Plot')
plt.show()

Here:
np.meshgrid() creates a 2D coordinate grid.
plot_surface() visualizes continuous 3D data.
cmap applies color mapping to show elevation or intensity.

✅ 5. 3D Wireframe Plot

A wireframe plot emphasizes structure rather than color.


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Z = np.sin(np.sqrt(X**2 + Y**2))
ax.plot_wireframe(X, Y, Z, color='black', linewidth=0.5)
ax.set_title('3D Wireframe Plot')
plt.show()

Wireframes are light and fast, making them great for large datasets.

✅ 6. 3D Contour Plot

You can also draw 3D contour lines using contour3D().


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Z = np.sin(np.sqrt(X**2 + Y**2))
ax.contour3D(X, Y, Z, 50, cmap='plasma')
ax.set_title('3D Contour Plot')
plt.show()

The number 50 defines how many contour levels to draw.

✅ 7. Customizing View Angles

You can rotate or tilt your 3D plot for better visualization using view_init().


ax.view_init(elev=30, azim=60)  # Elevation and azimuth angles

This is especially helpful when showcasing multiple angles of the same data.

✅ 8. Adding Colorbars

For surface or contour plots, add colorbars to represent value scales.


surf = ax.plot_surface(X, Y, Z, cmap='coolwarm')
fig.colorbar(surf, shrink=0.5, aspect=10)

This adds a side legend that improves interpretability.

✅ 9. Combining Multiple 3D Plots

You can visualize multiple 3D surfaces or data series in one figure.


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

Z1 = np.sin(np.sqrt(X**2 + Y**2))
Z2 = np.cos(np.sqrt(X**2 + Y**2))

ax.plot_surface(X, Y, Z1, cmap='viridis', alpha=0.6)
ax.plot_wireframe(X, Y, Z2, color='black', linewidth=0.3)
plt.title("Combined Surface and Wireframe")
plt.show()

The alpha parameter controls transparency, making overlaps visible.

✅ 10. 3D Bar Plot

Bar plots can also be extended to three dimensions using bar3d().


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

_x = np.arange(4)
_y = np.arange(3)
_xx, _yy = np.meshgrid(_x, _y)
x, y = _xx.ravel(), _yy.ravel()

top = x + y
bottom = np.zeros_like(top)
width = depth = 0.5

ax.bar3d(x, y, bottom, width, depth, top, shade=True)
ax.set_title("3D Bar Plot")
plt.show()

✅ 11. Customizing Axes and Labels

Labeling is as important in 3D as it is in 2D.


ax.set_xlabel('X Axis')
ax.set_ylabel('Y Axis')
ax.set_zlabel('Z Axis')

You can also limit ranges:


ax.set_xlim(-5, 5)
ax.set_ylim(-5, 5)
ax.set_zlim(-1, 1)

✅ 12. Saving 3D Plots

Just like 2D plots, 3D figures can be saved easily:


plt.savefig('3d_surface_plot.png', dpi=300, bbox_inches='tight')

✅ 13. Best Practices

  • Use plot_surface for continuous data and scatter for discrete points.
  • Keep the viewing angle simple to avoid visual distortion.
  • Always include axis labels and a colorbar for better interpretation.
  • For presentation visuals, combine plot_surface and wireframe with transparency.

✅ Summary

In this chapter, you learned to build 3D visualizations using Matplotlib’s mplot3d toolkit.
From 3D lines and scatter plots to surfaces, contours, and bars — you now have the skills to represent complex data in three dimensions.

In the next and final chapter, we’ll explore **how to integrate Matplotlib with Pandas and NumPy** for efficient data-driven plotting.

Leave a Reply

Your email address will not be published. Required fields are marked *