Master Matplotlib From Scratch

Learn Matplotlib fundamentals, figure anatomy, basic plotting, chart customization, subplots, statistical visualizations, color mapping, annotations, 3D plotting, animations, and interactive visualizations through structured practical lessons.

COURSE SYLLABUS
1. Introduction & Environment Setup
What is Matplotlib? Installation Environment Setup Imports and Conventions
2. Core Figure Anatomy & Structures
Figure vs Axes Creating Canvas Dimensions and Resolution Saving Visuals
3. Basic Plotting
Line Plots Scatter Plots Bar Charts Histograms
4. Basic Visual Formatting & Labels
Titles and Labels Text Customization Legends Grid Lines
5. Advanced Plot Customization
Format Strings Line and Marker Styling Color Systems Transparency
6. Axis Control, Ticks & Limits
Axis Limits Custom Ticks Tick Labels Axis Scaling
7. Multi-Plot Layouts & Subplots
Basic Subplots Indexing Subplots Layout Tuning Advanced Grids
8. Advanced Statistical & Data-Specific Plots
Pie Charts Box and Whisker Plots Violin Plots Error Bars
9. Color Mapping & 2D Data Visualizations
Colormaps Heatmaps and Images Colorbars Contour Plots
10. Annotations & Shapes
Basic Text Smart Annotations Drawing Shapes Shading Areas
11. Customizing Styles & Themes
Built-in Styles Custom Style Sheets Global Configurations
12. Object-Oriented API vs Pyplot
Pyplot vs Object-Oriented API Transitioning Methods Dual Axis Plots
13. Deep Integration with Pandas & Seaborn
Pandas Plotting Backend Seaborn Overlays Passing Axes
14. 3D Plotting
3D Setup 3D Lines and Scatter Surface and Wireframes Camera View
15. Dynamic & Live Plots
Interactive Mode Animation Module Real-time Updates Exporting Animations
16. Performance Optimization & Interactive Backends
Plotting Speed Interactive Backends Event Handling

3D Surface and Wireframe Plots

Learn how to create three-dimensional surface and wireframe plots using Matplotlib. Explore mesh grids, surface colors, colormaps, wireframe density and plot customization.

1. Learning Objectives

After completing this lesson, you will understand how to:

  • Understand 3D surface and wireframe plots.
  • Create coordinate grids using NumPy.
  • Use np.meshgrid() to generate grid coordinates.
  • Create surface plots using plot_surface().
  • Create wireframe plots using plot_wireframe().
  • Customize surface colors, transparency and mesh density.
  • Combine surface and wireframe visualizations.

2. Introduction to Surface and Wireframe Plots

A 3D surface plot represents a continuous surface in three-dimensional space. It uses X, Y and Z coordinate values to display how a value changes across two input dimensions.

A wireframe plot represents the same type of surface using a network of intersecting lines. It helps show the structure and shape of the surface without filling the entire area.

Surface Plot vs Wireframe Plot

Feature Surface Plot Wireframe Plot
Method ax.plot_surface() ax.plot_wireframe()
Appearance Displays a filled surface. Displays a network of lines.
Colors Supports surface colors and colormaps. Supports line colors.
Best for Visualizing continuous values and surface patterns. Understanding surface structure and mesh layout.

3. Understanding Mesh Grid

A mesh grid is a coordinate grid created from two one-dimensional coordinate arrays. It provides the X and Y positions required to calculate Z values for a 3D surface.

NumPy provides the np.meshgrid() function to create these coordinate matrices.

Example: Create a Mesh Grid

import numpy as np

x = np.linspace(-5, 5, 5)
y = np.linspace(-5, 5, 5)

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

print(X)
print(Y)

Output

X:
[[-5.  -2.5  0.   2.5  5. ]
 [-5.  -2.5  0.   2.5  5. ]
 [-5.  -2.5  0.   2.5  5. ]
 [-5.  -2.5  0.   2.5  5. ]
 [-5.  -2.5  0.   2.5  5. ]]

Y:
[[-5.  -5.  -5.  -5.  -5. ]
 [-2.5 -2.5 -2.5 -2.5 -2.5]
 [ 0.   0.   0.   0.   0. ]
 [ 2.5  2.5  2.5  2.5  2.5]
 [ 5.   5.   5.   5.   5. ]]
Tip: The X and Y arrays generated by np.meshgrid() have matching two-dimensional shapes. These arrays can be used to calculate the corresponding Z values.

4. Calculate Z Values for a Surface

After generating the X and Y coordinate grids, you can calculate Z values using a mathematical expression. The resulting Z array defines the height of the surface at each coordinate position.

Example: Mathematical Surface Function

import numpy as np

x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)

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

Z = X**2 + Y**2

print("X shape:", X.shape)
print("Y shape:", Y.shape)
print("Z shape:", Z.shape)

Output

X shape: (50, 50)
Y shape: (50, 50)
Z shape: (50, 50)

In this example, the Z value is calculated by adding the square of X and the square of Y at every grid position.

5. Create a Basic 3D Surface Plot

The plot_surface() method creates a filled 3D surface using X, Y and Z coordinate arrays.

Basic Syntax

ax.plot_surface(
    X,
    Y,
    Z
)

Example: Basic Surface Plot

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)

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

Z = X**2 + Y**2

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

ax.plot_surface(
    X,
    Y,
    Z
)

ax.set_title("Basic 3D Surface Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.tight_layout()
plt.show()

Output

Figure: Basic 3D Surface Plot

A smooth bowl-shaped 3D surface is displayed.
X-axis: X
Y-axis: Y
Z-axis: X² + Y²

The surface has its minimum height near the origin (0, 0).

6. Customize Surface Colors

You can customize a surface using the color and cmap parameters. A colormap assigns colors according to the numerical Z values.

Example: Surface with a Colormap

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 60)
y = np.linspace(-5, 5, 60)

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

Z = np.sin(np.sqrt(X**2 + Y**2))

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

surface = ax.plot_surface(
    X,
    Y,
    Z,
    cmap="viridis"
)

fig.colorbar(
    surface,
    ax=ax,
    label="Z Value",
    pad=0.1
)

ax.set_title("3D Surface with Viridis Colormap")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.show()

Output

Figure: 3D Surface with Viridis Colormap

A wave-shaped 3D surface is displayed.
Colormap: viridis
A colorbar represents the Z values.
Higher and lower surface values receive different colors.

Common Colormaps

Colormap Description
viridis Sequential color gradient.
plasma Bright sequential color gradient.
coolwarm Blue-to-red diverging colors.
cividis Perceptually uniform sequential colors.
inferno Dark-to-bright sequential colors.

7. Control Surface Appearance

The surface appearance can be customized using transparency, edge colors, line width and shading options.

Example: Transparent Surface

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

surface = ax.plot_surface(
    X,
    Y,
    Z,
    cmap="plasma",
    alpha=0.7,
    edgecolor="black",
    linewidth=0.2
)

ax.set_title("Customized 3D Surface")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.show()

Output

Figure: Customized 3D Surface

A plasma-colored surface is displayed.
Transparency: 0.7
Edge color: Black
Edge line width: 0.2

The surface edges are visible through the transparent appearance.
Tip: Use transparency when you need to display multiple overlapping 3D visual elements.

8. Create a Basic 3D Wireframe Plot

The plot_wireframe() method displays a 3D surface using a network of lines. Unlike a surface plot, it does not fill the space between the mesh lines.

Basic Syntax

ax.plot_wireframe(
    X,
    Y,
    Z
)

Example: Basic Wireframe Plot

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 20)
y = np.linspace(-5, 5, 20)

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

Z = np.sin(np.sqrt(X**2 + Y**2))

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

ax.plot_wireframe(
    X,
    Y,
    Z
)

ax.set_title("Basic 3D Wireframe Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.tight_layout()
plt.show()

Output

Figure: Basic 3D Wireframe Plot

A 3D wireframe representation of a wave-shaped surface is displayed.
The surface is represented by intersecting lines.
The spaces between the lines remain unfilled.

9. Customize Wireframe Appearance

You can customize wireframe plots using line colors, line width and row or column sampling.

Example: Customized Wireframe

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

ax.plot_wireframe(
    X,
    Y,
    Z,
    color="blue",
    linewidth=0.8,
    rstride=2,
    cstride=2
)

ax.set_title("Customized Wireframe Plot")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.show()

Output

Figure: Customized Wireframe Plot

A blue 3D wireframe is displayed.
Line width: 0.8
Row sampling interval: 2
Column sampling interval: 2

The mesh displays every second row and column of the input grid.

Important Wireframe Parameters

Parameter Purpose
color Sets the wireframe line color.
linewidth Controls the thickness of the lines.
rstride Controls the row sampling interval.
cstride Controls the column sampling interval.

10. Control Surface Mesh Density

Surface plots can contain many grid cells. You can control the number of displayed rows and columns using rstride and cstride, or by using rcount and ccount.

Example: Surface with Sampling Intervals

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

ax.plot_surface(
    X,
    Y,
    Z,
    cmap="viridis",
    rstride=3,
    cstride=3
)

ax.set_title("Surface with Reduced Mesh Density")

plt.show()

Output

Figure: Surface with Reduced Mesh Density

A 3D surface is displayed with reduced row and column sampling.
Row stride: 3
Column stride: 3

Fewer grid cells are rendered compared with the full-resolution grid.
Important: Use either stride parameters (rstride, cstride) or count parameters (rcount, ccount) when controlling surface sampling. Do not mix the two approaches in the same call.

11. Combine Surface and Wireframe Plots

You can display a wireframe on top of a surface by drawing both visualizations on the same 3D Axes object. This helps show the surface colors and the underlying mesh structure together.

Example: Surface with Wireframe Overlay

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-5, 5, 30)
y = np.linspace(-5, 5, 30)

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

Z = np.sin(np.sqrt(X**2 + Y**2))

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

ax.plot_surface(
    X,
    Y,
    Z,
    cmap="viridis",
    alpha=0.75,
    edgecolor="none"
)

ax.plot_wireframe(
    X,
    Y,
    Z,
    color="black",
    linewidth=0.4,
    rstride=3,
    cstride=3
)

ax.set_title("Surface with Wireframe Overlay")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.show()

Output

Figure: Surface with Wireframe Overlay

A colored 3D surface is displayed.
A black wireframe is drawn over the surface.
The surface colors represent height values.
The wireframe highlights the mesh structure.

12. Use Different Mathematical Surface Functions

You can create different surface shapes by changing the mathematical expression used to calculate Z values.

Example 1: Bowl-Shaped Surface

Z = X**2 + Y**2

Example 2: Wave-Shaped Surface

Z = np.sin(np.sqrt(X**2 + Y**2))

Example 3: Saddle-Shaped Surface

Z = X**2 - Y**2

Example: Display a Saddle Surface

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-4, 4, 50)
y = np.linspace(-4, 4, 50)

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

Z = X**2 - Y**2

fig = plt.figure(figsize=(9, 6))

ax = fig.add_subplot(
    111,
    projection="3d"
)

ax.plot_surface(
    X,
    Y,
    Z,
    cmap="coolwarm"
)

ax.set_title("Saddle-Shaped 3D Surface")
ax.set_xlabel("X-axis")
ax.set_ylabel("Y-axis")
ax.set_zlabel("Z-axis")

plt.show()

Output

Figure: Saddle-Shaped 3D Surface

A saddle-shaped surface is displayed.
The surface rises along one direction and falls along the other.
Colormap: coolwarm

13. Surface and Wireframe Methods Comparison

Method / Parameter Purpose
plot_surface() Creates a filled 3D surface.
plot_wireframe() Creates a 3D mesh of lines.
np.meshgrid() Creates coordinate matrices.
cmap Sets the surface colormap.
alpha Controls transparency.
edgecolor Sets the surface edge color.
rstride Controls row sampling interval.
cstride Controls column sampling interval.
linewidth Controls line thickness.

14. Common Mistakes

Mistake Explanation Solution
Missing mesh grid Surface methods require coordinate arrays with compatible dimensions. Use np.meshgrid().
Incorrect Z dimensions The Z array does not match the X and Y grid shapes. Calculate Z from the generated X and Y arrays.
Using 2D Axes A normal Axes object cannot create 3D surfaces. Use projection="3d".
Excessive mesh density Large grids may produce slow or cluttered plots. Adjust stride or count parameters.
Missing colorbar It becomes difficult to interpret color-based values. Add a colorbar when using numerical color mapping.
Incorrect function A wireframe and filled surface are different visualizations. Choose the appropriate plotting method.
Important: Before calling plot_surface() or plot_wireframe(), verify that X, Y and Z have compatible two-dimensional shapes.

15. Best Practices

  • Use NumPy to generate coordinate grids efficiently.
  • Use np.meshgrid() for X and Y coordinate matrices.
  • Ensure the Z array matches the dimensions of the coordinate grids.
  • Choose surface plots for filled continuous data representations.
  • Choose wireframes when the mesh structure is important.
  • Use suitable colormaps to represent numerical values.
  • Adjust mesh density for large datasets.
  • Use transparency carefully when combining multiple 3D elements.
  • Add axis labels and a meaningful chart title.

16. Practical Activity

3D Temperature Surface Visualization

Create a 3D surface plot that represents temperature values across a geographical grid.

Requirements:

  1. Create X and Y coordinate arrays using NumPy.
  2. Generate coordinate matrices using np.meshgrid().
  3. Calculate Z values using a mathematical temperature function.
  4. Create a 3D Axes object.
  5. Display the data using plot_surface().
  6. Apply a suitable colormap.
  7. Add a colorbar to represent temperature values.
  8. Create a second visualization using plot_wireframe().
  9. Customize the title, axis labels and viewing angle.

17. Practice Questions

  1. What is a 3D surface plot?
  2. What is a wireframe plot?
  3. Which method creates a filled 3D surface?
  4. Which method creates a wireframe plot?
  5. What is the purpose of np.meshgrid()?
  6. Why must X, Y and Z have compatible shapes?
  7. What is the purpose of the cmap parameter?
  8. How do you control surface transparency?
  9. What are rstride and cstride?
  10. How can you combine a surface and wireframe in one plot?

Summary

Matplotlib provides plot_surface() and plot_wireframe() to create three-dimensional surface and wireframe visualizations. Surface plots display filled continuous surfaces, while wireframe plots represent the same type of data using intersecting lines.

NumPy's meshgrid() function creates coordinate matrices from X and Y arrays. A mathematical function can then calculate the corresponding Z values required to construct the 3D surface.

Surface and wireframe plots support customization through colormaps, transparency, edge colors, line widths and mesh sampling parameters. These techniques help visualize mathematical functions and continuous datasets in three dimensions.