Home » Tutorial on 3D Surface Plots in Matplotlib

Tutorial on 3D Surface Plots in Matplotlib

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

3D surface plots are valuable for visualizing three-dimensional data and complex surfaces. They help to display data as a surface where the z-axis represents a third variable, while the x and y-axes represent the two-dimensional space.

Surface plots are commonly used to visualize functions, topographies, and data distributions in three dimensions.

In this tutorial, we’ll explore how to create and customize 3D surface plots in Matplotlib, covering basic surface plots, colormaps, wireframes, adding color bars, customizing viewing angles, plotting parametric surfaces, and overlaying contours.

To start, we need to import the necessary libraries, including Axes3D from mpl_toolkits.mplot3d to enable 3D plotting.

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

1. Basic 3D Surface Plot

A basic 3D surface plot can be created using plot_surface, which requires x, y, and z data points to define the surface.

# Generate sample data
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 basic 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')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("Basic 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.
  • X and Y represent the grid in the XY plane, while Z contains the z-axis values.

2. Adding a Color Bar

Adding a color bar helps to interpret the color scale, which represents the Z values of the surface.

# Surface plot with color bar
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z, cmap='coolwarm')
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 Color Bar")
plt.show()

In this example:

  • fig.colorbar(surface, ax=ax, label=”Z value”) adds a color bar, indicating the Z values represented by each color.

3. Customizing Surface Plot Colors with Colormaps

Matplotlib offers various colormaps that can be used to enhance the visual appeal of surface plots. Here’s an example using a different colormap.

# 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')
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, providing a unique color gradient based on Z values.

4. Wireframe and Surface Plot Combined

You can combine a surface plot with a wireframe to add structure and enhance the 3D effect.

# Overlayed surface and wireframe plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Surface plot
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.7)

# Wireframe overlay
ax.plot_wireframe(X, Y, Z, color='black', linewidth=0.5)

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("Overlayed Surface and Wireframe Plot")
plt.show()

In this example:

  • alpha=0.7 makes the surface plot partially transparent, allowing the wireframe to show through.
  • plot_wireframe adds a grid structure over the surface, enhancing visibility.

5. Adjusting the Viewing Angle

You can adjust the viewing angle using view_init, which sets the elevation and azimuth.

# Surface plot with custom viewing angle
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='coolwarm', 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 azimuth to 45 degrees for a different perspective.

6. Plotting a Parametric Surface

Parametric surfaces are useful for visualizing functions dependent on two parameters. Here’s an example using spherical coordinates.

# Generate parametric data for a sphere
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 50)
U, V = np.meshgrid(u, v)
X = np.sin(V) * np.cos(U)
Y = np.sin(V) * np.sin(U)
Z = np.cos(V)

# Create a parametric surface plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='inferno', edgecolor='none')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("Parametric Surface Plot (Sphere)")
plt.show()

In this example:

  • U and V represent azimuthal and polar angles, while X, Y, and Z are calculated to form a sphere.

7. Adding Contours to Surface Plots

Contour lines can be added to a 3D surface plot to show the Z-value levels on the XY plane, giving additional information about the surface structure.

# Surface plot with contour projections
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')

# Surface plot
ax.plot_surface(X, Y, Z, cmap='viridis', edgecolor='none')

# Contour projection on the XY plane
ax.contour(X, Y, Z, levels=10, cmap='viridis', offset=-1, zdir='z')

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

In this example:

  • ax.contour(X, Y, Z, levels=10, offset=-1, zdir='z') adds a contour projection on the XY plane with a Z offset of -1.

8. Surface Plot with Custom Z-Scale (Logarithmic Scale)

Using a logarithmic scale for the Z-axis is helpful when the data spans multiple orders of magnitude.

# Generate data for logarithmic surface plot
Z_log = np.exp(Z / 2)  # Apply exponential function for large Z values

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
surface = ax.plot_surface(X, Y, Z_log, cmap='magma', edgecolor='none')
ax.set_zscale('log')  # Apply logarithmic scale to Z-axis
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis (Log Scale)")
plt.title("3D Surface Plot with Logarithmic Z-Scale")
plt.show()

In this example:

  • ax.set_zscale(‘log') applies a logarithmic scale to the Z-axis, which can make it easier to interpret data with a large range of values.

9. Surface Plot with Transparency (Alpha)

Adding transparency to a surface plot can help reveal additional details when overlaying multiple surfaces or adding contours.

# Surface plot with transparency
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='cool', alpha=0.6)
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot with Transparency")
plt.show()

In this example:

  • alpha=0.6 makes the surface plot 60% transparent, allowing for better visualization of underlying details if overlaid.

10. Overlaying Multiple Surface Plots

You can overlay multiple surface plots in the same 3D space to compare different datasets or functions.

# Generate an additional surface for comparison
Z2 = np.cos(np.sqrt(X**

2 + Y**2))

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

# First surface plot
ax.plot_surface(X, Y, Z, cmap='viridis', alpha=0.7, edgecolor='none')

# Second surface plot
ax.plot_surface(X, Y, Z2, cmap='plasma', alpha=0.5, edgecolor='none')

ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("Overlayed 3D Surface Plots")
plt.show()

In this example:

  • Two surface plots are created with different colormaps (viridis and plasma).
  • alpha is used to make each surface semi-transparent, allowing both to be visible.

11. Surface Plot with Custom Grid Density

You can adjust the density of the surface plot grid by changing the resolution of the X and Y data. This affects the level of detail in the surface.

# Lower resolution data for coarse surface plot
x_coarse = np.linspace(-5, 5, 30)
y_coarse = np.linspace(-5, 5, 30)
X_coarse, Y_coarse = np.meshgrid(x_coarse, y_coarse)
Z_coarse = np.sin(np.sqrt(X_coarse**2 + Y_coarse**2))

# Surface plot with coarse grid
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X_coarse, Y_coarse, Z_coarse, cmap='coolwarm', edgecolor='none')
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")
plt.title("3D Surface Plot with Coarse Grid")
plt.show()

In this example:

  • Using fewer points for x and y creates a coarser surface plot, reducing the number of grid lines and creating a simpler, less detailed surface.

Summary

In this tutorial, we covered various techniques to create and customize 3D surface plots in Matplotlib:

  1. Basic 3D Surface Plot to visualize a surface in 3D space.
  2. Adding a Color Bar for easy interpretation of Z values.
  3. Using Colormaps to add visual depth.
  4. Overlaying Surface with Wireframe for additional structure.
  5. Adjusting Viewing Angle to change the perspective.
  6. Parametric Surface Plot for complex shapes.
  7. Adding Contours to show level lines on the XY plane.
  8. Custom Z-Scale (Logarithmic) for data with large ranges.
  9. Adding Transparency to allow multiple surfaces to overlap.
  10. Overlaying Multiple Surfaces for comparison.
  11. Custom Grid Density to control the detail level.

These techniques provide a comprehensive guide to creating informative and visually appealing 3D surface plots, allowing you to effectively visualize complex three-dimensional data.

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