Home » Tutorial on 3D Plotting in Matplotlib

Tutorial on 3D Plotting in Matplotlib

Oracle Java Certification
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Spring Framework Basics Video Course
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

3D plotting is a powerful tool for visualizing three-dimensional data and relationships.

Matplotlib’s mplot3d toolkit provides several ways to create 3D plots, including line plots, scatter plots, surface plots, wireframe plots, contour plots, and bar plots.

These plots help in exploring spatial relationships and patterns within data, making 3D plotting a valuable asset in data visualization.

In this tutorial, we’ll explore how to create and customize various 3D plots in Matplotlib, covering the basics, surface plots, scatter plots, wireframes, bar plots, contour projections, and more.

Getting Started with 3D Plotting

To create 3D plots in Matplotlib, you need to import the Axes3D module from the mpl_toolkits.mplot3d library. Then, you can add a 3D subplot to your figure using fig.add_subplot(projection='3d').

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

1. Basic 3D Line Plot

A 3D line plot is similar to a 2D line plot but with an additional z-coordinate.

# Generate sample data
t = np.linspace(0, 20, 100)
x = np.sin(t)
y = np.cos(t)
z = t

# Create a 3D line plot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z, color='blue')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Line Plot")
plt.show()

In this example:

  • ax.plot(x, y, z, color='blue') plots a 3D line with the x, y, and z coordinates.

2. 3D Scatter Plot

A 3D scatter plot displays individual points in a 3D space, making it useful for visualizing clusters and spatial patterns.

# Generate random 3D data
np.random.seed(0)
x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.random.standard_normal(100)

# Create a 3D scatter plot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x, y, z, color='purple', marker='o')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Scatter Plot")
plt.show()

In this example:

  • ax.scatter(x, y, z, color='purple', marker='o') creates a 3D scatter plot with circular markers.

3. 3D Surface Plot

Surface plots display a 3D surface defined by a grid of x, y, and z values. They are useful for visualizing functions and topography.

# Generate data for surface plot
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))

# Create a 3D surface plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
fig.colorbar(surface, ax=ax, shrink=0.5, aspect=5, label="Z value")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot")
plt.show()

In this example:

  • ax.plot_surface(X, Y, Z, cmap='viridis') creates a 3D surface plot with the viridis colormap.
  • fig.colorbar(surface) adds a color bar to represent the Z values.

4. 3D Wireframe Plot

A wireframe plot is similar to a surface plot but only displays the edges, creating a grid-like structure.

# Create a 3D wireframe plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(X, Y, Z, color='green')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Wireframe Plot")
plt.show()

In this example:

  • ax.plot_wireframe(X, Y, Z, color='green') creates a wireframe plot with green lines.

5. 3D Contour Plot

Contour plots on 3D surfaces help visualize contours projected onto the XY plane.

# Create a 3D contour plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
contour = ax.contour3D(X, Y, Z, levels=20, cmap='cool')
fig.colorbar(contour, ax=ax, label="Z value")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Contour Plot")
plt.show()

In this example:

  • ax.contour3D(X, Y, Z, levels=20, cmap='cool') creates a 3D contour plot with 20 contour levels.

6. 3D Bar Plot

A 3D bar plot is useful for visualizing categorical data in three dimensions, where the height of each bar represents a value.

# Generate data for 3D bar plot
x = np.arange(5)
y = np.arange(5)
x, y = np.meshgrid(x, y)
x = x.ravel()
y = y.ravel()
z = np.zeros_like(x)
dz = np.random.rand(25) * 10  # Random heights for each bar

# Create a 3D bar plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.bar3d(x, y, z, dx=0.5, dy=0.5, dz=dz, color='lightblue', edgecolor='black')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Bar Plot")
plt.show()

In this example:

  • ax.bar3d(x, y, z, dx=0.5, dy=0.5, dz=dz) creates a 3D bar plot, where dz represents the height of each bar.

7. Adding Color Maps to Surface Plots

Surface plots can be customized with various colormaps to add more information and visual appeal.

# Surface plot with custom colormap
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z, cmap='plasma', edgecolor='none')
fig.colorbar(surface, ax=ax, shrink=0.5, aspect=5, label="Z value")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot with Plasma Colormap")
plt.show()

In this example:

  • cmap='plasma' applies the plasma colormap, giving the plot a vibrant color gradient based on Z values.

8. Customizing the Viewing Angle

You can control the angle of the 3D plot using view_init, which adjusts the elevation and azimuth angles.

# Surface plot with a custom viewing angle
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='inferno', edgecolor='none')
ax.view_init(elev=30, azim=45)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot with Custom Viewing Angle")
plt.show()

In this example:

  • ax.view_init(elev=30, azim=45) sets the elevation to 30 degrees and the azimuth angle to 45 degrees.

9. 3D Parametric Plot

A parametric plot is useful for plotting functions that depend on a parameter. Here’s an example of a parametric helix.

# Generate parametric data
t = np.linspace(0, 10, 100)
x = np.sin(t)
y = np.cos(t)
z = t

# Create a 3D parametric plot
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
ax.plot(x, y, z, color='purple')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Parametric Plot (Helix)")
plt.show()

In this example:

  • t is a parameter, with x, y, and z defined as functions of t.

10. 3D Scatter Plot with Color and Size

You can customize a 3D scatter plot by

mapping the color and size of the points to additional variables.

# Generate random data with color and size attributes
x = np.random.standard_normal(100)
y = np.random.standard_normal(100)
z = np.random.standard_normal(100)
colors = np.random.rand(100)
sizes = np.random.rand(100) * 100

# Create a 3D scatter plot with color and size variation
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
scatter = ax.scatter(x, y, z, c=colors, s=sizes, cmap='viridis', alpha=0.7)
fig.colorbar(scatter, ax=ax, label="Color Intensity")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Scatter Plot with Color and Size Variation")
plt.show()

In this example:

  • c=colors and s=sizes control the color and size of each point, respectively.
  • cmap='viridis' applies a colormap to the scatter plot.

11. 3D Contour Plot on 2D Plane (Projected Contours)

You can create a contour plot on the XY plane below a 3D surface plot to show projected contours.

# Surface plot with projected contour on the XY plane
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')
ax.contour(X, Y, Z, levels=10, cmap='cool', linestyles='solid', offset=-1)

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot with Projected Contours on XY Plane")
plt.show()

In this example:

  • ax.contour(X, Y, Z, levels=10, cmap='cool', offset=-1) adds contours projected onto the XY plane, with offset=-1 controlling the Z position of the projection.

Summary

In this tutorial, we covered a variety of ways to create and customize 3D plots in Matplotlib:

  1. Basic 3D Line Plot to show paths in 3D space.
  2. 3D Scatter Plot for visualizing individual points in a 3D space.
  3. 3D Surface Plot for displaying functions and topography.
  4. 3D Wireframe Plot to show gridlines without filling.
  5. 3D Contour Plot for contour levels on a 3D surface.
  6. 3D Bar Plot for visualizing categorical data.
  7. Surface Plot with Color Maps to add visual depth.
  8. Custom Viewing Angle for better perspective control.
  9. 3D Parametric Plot to plot parameter-dependent functions.
  10. 3D Scatter Plot with Color and Size for detailed data points.
  11. Projected Contours on XY Plane for contours below a surface plot.

These examples demonstrate the versatility of 3D plotting in Matplotlib, allowing you to visualize data with additional dimensions and gain deeper insights into spatial relationships.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More