October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
Redmond desk4 min

Create a Matplotlib 3D Scatter Plot with a Line and Surface

Use one Matplotlib 3D axes to plot XYZ observations, a connected line, and a surface built from coordinate grids.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To combine a 3D scatter plot, a line, and a surface in Matplotlib, create one 3D axes and add all three with its methods: ax.scatter(), ax.plot(), and ax.plot_surface(). A regular surface requires matching coordinate grids for X, Y, and Z; the points and line use their own x, y, and z coordinates. The example below puts them together on one set of axes.

Complete example: points, line, and surface on one 3D plot

This example uses a regular grid for the surface, three illustrative observations, and a separate line. Replace the example coordinates and surface formula with your data. The line and observations should use coordinate units and scales consistent with the surface.

import matplotlib.pyplot as plt
import numpy as np

# Create a rectangular grid and calculate a Z value at every X, Y pair.
x_grid = np.linspace(-5, 5, 50)
y_grid = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x_grid, y_grid)
Z = np.sin(np.sqrt(X**2 + Y**2))

# Example XYZ observations.
x_pts = np.array([0.0, 1.0, 2.0])
y_pts = np.array([0.0, 1.0, 0.5])
z_pts = np.array([0.2, 0.8, 0.6])

# Example XYZ line.
x_line = np.linspace(-4, 4, 100)
y_line = np.zeros_like(x_line)
z_line = 0.5 * np.sin(x_line)

fig = plt.figure()
ax = fig.add_subplot(projection="3d")

surface = ax.plot_surface(X, Y, Z, cmap="coolwarm", linewidth=0)
ax.scatter(x_pts, y_pts, z_pts, color="black", marker="o", label="Observations")
ax.plot(x_line, y_line, z_line, color="crimson", label="Line")

ax.set_xlabel("X")
ax.set_ylabel("Y")
ax.set_zlabel("Z")
ax.legend()
fig.colorbar(surface, ax=ax, shrink=0.6, label="Surface Z")

plt.show()

The surface variable holds the surface artist returned by plot_surface; passing it to fig.colorbar creates a color key for the surface colormap. The example follows Matplotlib’s documented 3D axes, scatter, surface-grid, and colorbar patterns: mplot3d toolkit guide, 3D scatterplot example, and 3D surface example.

How the three plot elements fit together

Create one 3D axes

fig.add_subplot(projection="3d") returns an axes object that supports Matplotlib’s 3D methods. Add the surface, scatter points, and line to that same ax so they share one coordinate system. Another documented setup is plt.subplots(subplot_kw={"projection": "3d"}). Matplotlib’s current stable documentation is version 3.11.2 as accessed on October 4, 2026; its guide notes that before Matplotlib 3.2.0, this projection route required an explicit mpl_toolkits.mplot3d import. See the mplot3d toolkit guide.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Add observations and a connected line

Call ax.scatter(xs, ys, zs) with the three coordinates for your discrete observations. Call ax.plot(x_line, y_line, z_line) with the line’s coordinate arrays. They are separate inputs: a trajectory should not be created by connecting scatter points unless that is the relationship you intend to show. The Axes3D API reference documents both methods.

Build the surface from coordinate grids

For a regular surface, create two-dimensional X and Y coordinate grids, then calculate or supply a corresponding Z value at each grid position. NumPy’s meshgrid turns the one-dimensional x and y coordinates into those grids. Pass the resulting X, Y, and Z arrays to ax.plot_surface(X, Y, Z). The official surface example demonstrates this pattern; the Axes3D API reference documents the method.

Choose the surface method that matches your data

Surface method Best fit Input shape
plot_surface(X, Y, Z) A surface represented on a rectangular grid Corresponding X, Y, and Z coordinate grids
plot_trisurf(...) Surface samples that are not arranged on a rectangular grid and are represented with triangles Triangulated, non-grid data; consult the Axes3D API reference for the supported arguments

Both methods are documented by Matplotlib; the useful distinction is the topology of the input data. Use plot_surface when you have a grid, and consider plot_trisurf for irregular samples that can be triangulated.

Make the combined plot easier to read

  • Label the coordinates. Set ax.set_xlabel(), ax.set_ylabel(), and ax.set_zlabel() to identify what each axis represents. The official 3D scatterplot example labels all three.
  • Use distinct visual styles. Choose point markers and a line color that contrast with the surface. A surface can obscure points or line segments behind it, so inspect the rendered view rather than assuming every element will remain visible.
  • Use a colorbar when color carries meaning. If the surface colormap represents Z values, add a colorbar using the surface artist, as in the complete example and Matplotlib’s surface example.
  • Adjust the view when overlap or shape is confusing. The Axes3D API provides axis limits, aspect controls, and view_init; its elevation and azimuth arguments are angles in degrees. Change the view to make relationships visible, while keeping in mind that the displayed scene is a projection.

Transparency, surface density, point count, rendering backend, and output format can all affect legibility. There is no universal alpha or density setting established by the cited documentation, so inspect the output in the environment where it will be viewed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

What Matplotlib’s 3D view represents

mplot3d provides 3D plotting within Matplotlib by projecting the scene into 2D. This makes it convenient when a plot belongs in a Matplotlib workflow, but the projection can make depth and overlap ambiguous. The Matplotlib guide describes mplot3d as a simple 3D plotting toolkit, not the fastest or most feature-complete 3D library. For a combined scatter, line, and surface, check occlusion and view angle before relying on the image to communicate which element is in front. See the mplot3d toolkit guide.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.