3D Plots in Plotly: Scatter, Surface, Line, and Mesh

Make interactive 3D plots in Plotly: scatter points with px.scatter_3d, surfaces with go.Surface, 3D lines and meshes, plus camera angles, aspect ratio and axis settings.

Make a 3D scatter plot in Plotly with px.scatter_3d(df, x=..., y=..., z=...), and a 3D surface with go.Figure(go.Surface(x=x, y=y, z=z)), where z is a 2D grid of heights. Both are interactive: drag to rotate, scroll to zoom, and hover to read values.

Quick Example

Made-up measurements from 180 coffee roasts:

import numpy as np
import pandas as pd
import plotly.express as px

rng = np.random.default_rng(103)
frames = []
for roast, temp, minutes, acidity in [("Light", 200, 9.0, 7.4),
                                      ("Medium", 214, 11.0, 6.0),
                                      ("Dark", 228, 13.0, 4.4)]:
    t = rng.normal(temp, 3.5, 60)
    m = rng.normal(minutes, 0.7, 60)
    a = acidity - 0.05 * (t - temp) - 0.2 * (m - minutes) + rng.normal(0, 0.25, 60)
    frames.append(pd.DataFrame({"roast": roast, "temp_c": t, "minutes": m, "acidity": a}))
roasts = pd.concat(frames, ignore_index=True)

fig = px.scatter_3d(roasts, x="temp_c", y="minutes", z="acidity", color="roast",
                    color_discrete_sequence=["#e9a23b", "#b45309", "#4a2511"],
                    labels={"temp_c": "Temperature (°C)", "minutes": "Roast time (min)",
                            "acidity": "Acidity score", "roast": "Roast"},
                    title="Hotter, longer roasts are less acidic", height=520)
fig.update_traces(marker_size=4)
fig.update_layout(margin=dict(l=0, r=0, b=0, t=50),
                  scene_camera_eye=dict(x=1.6, y=1.6, z=1.0))
fig.show()

Plotly 3D scatter plot of coffee roasts by temperature, roast time and acidity, with light, medium and dark roasts forming three groups

The three roasts form separate clouds: acidity drops from light to dark as temperature and time go up. margin is tightened because 3D scenes leave a lot of empty space by default, and scene_camera_eye moves the viewpoint back so the axis labels fit. The code targets Plotly 6.x.

3D Scatter: Size, Symbol, and Opacity

px.scatter_3d takes the same encodings as a 2D scatter plot. size scales markers by a column, symbol changes their shape, and opacity helps when points overlap.

roasts["batch_kg"] = rng.uniform(5, 30, len(roasts)).round(1)

fig = px.scatter_3d(roasts, x="temp_c", y="minutes", z="acidity", color="acidity",
                    size="batch_kg", size_max=18, opacity=0.75, symbol="roast",
                    symbol_sequence=["circle", "diamond", "square"],
                    color_continuous_scale="Viridis", hover_data=["batch_kg"],
                    title="Color by value, size by batch weight", width=800, height=560)
fig.update_layout(legend=dict(orientation="h", y=0, x=0),
                  margin=dict(l=0, r=0, b=0, t=50),
                  scene_camera_eye=dict(x=1.6, y=1.6, z=1.0))
fig.show()

3D scatter plot with marker color showing acidity, marker size showing batch weight and marker shape showing roast level

3D scatter markers support only a few symbols: circle, square, and diamond (each with an -open version), plus cross and x. A continuous color bar and a symbol legend compete for the right side, so the legend moves to the bottom here.

3D Surface Plot

A surface needs heights on a regular grid. z is a 2D array with one row for each y value and one column for each x value, which is what NumPy's meshgrid produces.

import plotly.graph_objects as go

x = np.linspace(0, 8, 90)     # km east
y = np.linspace(0, 6, 70)     # km north
xx, yy = np.meshgrid(x, y)

def hill(cx, cy, spread, height):
    return height * np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * spread ** 2))

z = hill(2.6, 3.4, 1.0, 620) + hill(5.7, 2.2, 1.3, 340) + hill(4.4, 4.6, 0.6, 150)

fig = go.Figure(go.Surface(
    x=x, y=y, z=z, colorscale="Earth", colorbar=dict(title="m", len=0.7),
    contours_z=dict(show=True, start=50, end=600, size=50, color="#334155",
                    project_z=True),
))
fig.update_layout(
    title="Elevation of a made-up island", height=540,
    margin=dict(l=0, r=0, b=0, t=50),
    scene=dict(xaxis_title="East (km)", yaxis_title="North (km)",
               zaxis=dict(title="Elevation (m)", range=[-450, 700]),
               aspectratio=dict(x=1.3, y=1, z=0.8),
               camera_eye=dict(x=1.7, y=1.7, z=1.0)),
)
fig.show()

Plotly 3D surface plot of island elevation with a tall peak, a lower second hill and contour lines projected onto the floor

contours_z draws a line every 50m of height on the surface, and project_z=True copies those lines onto the floor. The z-axis starts well below zero to leave room to see the copy. If x and y don't match the shape of z, Plotly doesn't raise an error, so a stretched or clipped surface is a sign to check that z.shape == (len(y), len(x)).

Surface From a Table of x, y, z Columns

Gridded data often arrives as one row per point. pivot turns it into the 2D shape go.Surface expects:

points = pd.DataFrame({"east": xx.ravel(), "north": yy.ravel(), "elevation": z.ravel()})

grid = points.pivot(index="north", columns="east", values="elevation")
surface = go.Surface(x=grid.columns, y=grid.index, z=grid.values)
print(grid.shape)    # (70, 90)

Scattered points that don't sit on a grid need interpolating first (SciPy's griddata), or a mesh, shown below.

Set the Camera Angle

scene_camera.eye is the viewpoint, measured from the center of the plot. Larger numbers move the camera farther away. The default is x=1.25, y=1.25, z=1.25.

fig = go.Figure(go.Surface(x=x, y=y, z=z, colorscale="Earth", showscale=False))
fig.update_layout(
    title="Looking from the south, slightly above", template="plotly_white",
    width=800, height=460, margin=dict(l=0, r=0, b=0, t=50),
    scene_camera=dict(eye=dict(x=0, y=-2.0, z=0.7)),
    scene_aspectratio=dict(x=1.3, y=1, z=0.6),
)
fig.show()

The island surface viewed from the south at a low angle

View eye
Default dict(x=1.25, y=1.25, z=1.25)
From above dict(x=0, y=0, z=2.5)
From the front dict(x=0, y=-2.2, z=0)
From the side dict(x=2.2, y=0, z=0)

Axis Titles, Ranges, and Aspect Ratio

3D axes belong to the scene, not to layout.xaxis. Calling fig.update_xaxes() on a 3D chart runs without an error and changes nothing you can see. Use fig.update_scenes() or fig.update_layout(scene=dict(...)).

aspectmode sets the shape of the box: "data" draws the axes in proportion to their ranges, "cube" makes them equal, and "manual" uses your aspectratio.

fig = px.scatter_3d(roasts, x="temp_c", y="minutes", z="acidity",
                    color_discrete_sequence=["#b45309"], template="plotly_white",
                    title="Cube box with custom axis settings", width=800, height=500)
fig.update_traces(marker_size=3)
fig.update_scenes(
    aspectmode="cube",
    xaxis=dict(title="°C", dtick=10, backgroundcolor="#fef3c7"),
    yaxis=dict(title="Minutes", range=[6, 16], backgroundcolor="#fde68a"),
    zaxis=dict(title="Acidity", nticks=5, backgroundcolor="#fffbeb"),
)
fig.update_layout(margin=dict(l=0, r=0, b=0, t=50),
                  scene_camera_eye=dict(x=1.7, y=1.7, z=1.1))
fig.show()

3D scatter plot in a cube shaped box with tinted walls and custom tick spacing

3D Line Plot

px.line_3d connects rows in the order they appear. Here it traces a drone climbing in a widening spiral:

steps = np.linspace(0, 1, 300)
flight = pd.DataFrame({
    "east": (20 + 60 * steps) * np.cos(8 * np.pi * steps),
    "north": (20 + 60 * steps) * np.sin(8 * np.pi * steps),
    "altitude": 120 * steps,
})

fig = px.line_3d(flight, x="east", y="north", z="altitude", title="Drone flight path (m)",
                 template="plotly_white", width=800, height=500)
fig.update_traces(line=dict(width=6, color=flight["altitude"], colorscale="Plasma"))
fig.update_layout(margin=dict(l=0, r=0, b=0, t=50),
                  scene_camera_eye=dict(x=1.6, y=1.6, z=1.0))
fig.show()

3D line plot of a widening spiral flight path colored by altitude

Plot Points on Top of a Surface

Add a go.Scatter3d trace to the same figure. Raise the points a little so the surface doesn't hide half of each marker.

peaks = pd.DataFrame({"name": ["North Peak", "East Hill"], "east": [2.6, 5.7],
                      "north": [3.4, 2.2]})
peaks["elevation"] = [grid.values[np.abs(y - r.north).argmin(), np.abs(x - r.east).argmin()]
                      for r in peaks.itertuples()]

fig = go.Figure([
    go.Surface(x=x, y=y, z=z, colorscale="Greens", reversescale=True, showscale=False),
    go.Scatter3d(x=peaks["east"], y=peaks["north"], z=peaks["elevation"] + 60,
                 mode="markers+text", text=peaks["name"], textposition="top center",
                 marker=dict(size=6, color="#dc2626")),
])
fig.update_layout(title="Labeled summits", template="plotly_white", width=800, height=500,
                  margin=dict(l=0, r=0, b=0, t=50), scene_aspectratio=dict(x=1.3, y=1, z=0.6),
                  scene_zaxis_range=[0, 800])
fig.show()

Island surface in green with two red points labeled North Peak and East Hill

Mesh3d for Irregular Points

go.Mesh3d builds a surface from loose points by connecting them into triangles. No grid is needed.

n = 500
px_ = rng.uniform(0, 8, n)
py_ = rng.uniform(0, 6, n)
pz_ = (620 * np.exp(-((px_ - 2.6) ** 2 + (py_ - 3.4) ** 2) / 2)
       + 340 * np.exp(-((px_ - 5.7) ** 2 + (py_ - 2.2) ** 2) / (2 * 1.3 ** 2)))

fig = go.Figure(go.Mesh3d(x=px_, y=py_, z=pz_, intensity=pz_, colorscale="Cividis",
                          flatshading=True, colorbar=dict(title="m", len=0.7)))
fig.update_layout(title="Mesh from 500 survey points", template="plotly_white",
                  width=800, height=500, margin=dict(l=0, r=0, b=0, t=50),
                  scene_aspectratio=dict(x=1.3, y=1, z=0.6))
fig.show()

Triangulated 3D mesh of two hills built from 500 random survey points

By default the triangles are chosen by looking at the x-y plane, which suits terrain-like data. For closed 3D shapes, set alphahull or pass the triangle corners yourself with i, j, and k.

Two 3D Plots Side by Side

Give each subplot the type "scene". The scenes are named scene and scene2 and are configured separately.

from plotly.subplots import make_subplots

fig = make_subplots(rows=1, cols=2, specs=[[{"type": "scene"}, {"type": "scene"}]],
                    subplot_titles=["Surface", "Wireframe style"], horizontal_spacing=0.02)
fig.add_trace(go.Surface(x=x, y=y, z=z, colorscale="Earth", showscale=False), row=1, col=1)
fig.add_trace(go.Surface(
    x=x, y=y, z=z, showscale=False, hidesurface=True,
    contours=dict(x=dict(show=True, start=0, end=8, size=0.4, color="#334155"),
                  y=dict(show=True, start=0, end=6, size=0.4, color="#334155")),
), row=1, col=2)
fig.update_scenes(aspectratio=dict(x=1.3, y=1, z=0.7),
                  camera_eye=dict(x=1.4, y=-1.4, z=1.0))
fig.update_layout(template="plotly_white", width=900, height=420,
                  margin=dict(l=0, r=0, b=0, t=40))
fig.show()

The island drawn twice, as a colored surface and as a wireframe

See make_subplots for grids that mix 2D and 3D charts.

Common Problems

  • The chart area is blank. Plotly 3D charts use WebGL. Browsers limit how many WebGL contexts a page can hold, so a notebook or web page with many 3D charts can leave some empty. Show fewer at once, or export static images.
  • Axis titles don't change. Update the scene, not xaxis.
  • The surface looks flipped or stretched. Check that z has shape (len(y), len(x)); try z.T.
  • Hills look flat or spiky. Set aspectratio. Plotly doesn't keep real-world proportions unless you ask for them.

To share a chart that still rotates, save it as a standalone HTML file. fig.write_image() saves a single view, taken from the camera angle you set.

Should You Use a 3D Plot?

Use one when the shape is the point, as with terrain or a response surface, and readers can rotate it. For comparing values, a heatmap or a 2D scatter plot with color is easier to read, especially in a static report. If you need 3D charts for print, see 3D plots in Matplotlib.

Similar Topics