To make an interactive scatter plot in Plotly, call px.scatter(df, x="col_a", y="col_b"). Add color= to color points by a column, size= to scale them, hover_name= for the bold title in the tooltip, and trendline="ols" for a fitted line. Each row of the DataFrame becomes one point. The examples use Plotly 6.9 and also run on Plotly 7.
Quick Example
Hover over a point to see the trail's name and details:
import numpy as np
import pandas as pd
import plotly.express as px
rng = np.random.default_rng(64)
n = 90
difficulty = rng.choice(["Easy", "Moderate", "Hard"], n, p=[0.35, 0.4, 0.25])
distance = np.select(
[difficulty == "Easy", difficulty == "Moderate"],
[rng.gamma(4, 1.4, n), rng.gamma(6, 1.6, n)], rng.gamma(7, 2.1, n)).round(1)
climb_per_km = pd.Series(difficulty).map({"Easy": 45, "Moderate": 70, "Hard": 95})
trails = pd.DataFrame({
"trail": [f"Trail {i + 1}" for i in range(n)],
"difficulty": difficulty,
"distance_km": distance,
"climb_m": (climb_per_km * distance + rng.normal(0, 80, n)).clip(lower=20).round(),
"rating": rng.normal(4.2, 0.35, n).clip(2.5, 5).round(1),
"reviews": rng.lognormal(4, 0.9, n).round().astype(int),
})
fig = px.scatter(
trails, x="distance_km", y="climb_m", color="difficulty", size="reviews",
hover_name="trail", size_max=30,
category_orders={"difficulty": ["Easy", "Moderate", "Hard"]},
color_discrete_map={"Easy": "#52b788", "Moderate": "#f4a261", "Hard": "#9d4edd"},
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)",
"difficulty": "Difficulty", "reviews": "Reviews"},
title="Hiking trails by length and climb",
)
fig.show()
Easy trails stay short and flat, while hard ones are longer and climb about twice as much per kilometer. labels= renames the columns everywhere they appear: axis titles, the legend, and the hover text. category_orders= fixes the legend order, which otherwise follows the order the values first appear in the data.
Color points by a number
When the color column is numeric, Plotly draws a continuous colorscale and a colorbar instead of a legend. color_continuous_scale= picks the scale, and range_color= fixes its ends:
fig = px.scatter(
trails, x="distance_km", y="climb_m", color="rating",
color_continuous_scale="Viridis", range_color=[3, 5],
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)",
"rating": "Rating"},
width=800, height=450,
)
fig.update_traces(marker=dict(size=10, line=dict(width=0.5, color="white")))
fig.show()

Ratings here don't depend on length, so the colors are mixed. If a numeric column is really a set of categories (bedrooms, year), convert it with .astype(str) to get discrete colors and a legend. update_traces(marker=...) sets one size and a white outline for every point when you're not using size=.
How do I change the hover text?
hover_name= sets the bold line at the top of the tooltip. hover_data= adds, hides, or formats the other lines: a column name with True adds it, False hides it, and a format string like ":.1f" formats it:
fig = px.scatter(
trails, x="distance_km", y="climb_m", color="difficulty", hover_name="trail",
hover_data={"rating": ":.1f", "reviews": ":,", "difficulty": False},
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)"},
width=800, height=450,
)
fig.show()
Hiding difficulty removes a line the color already shows. For full control of the tooltip layout, set hovertemplate with fig.update_traces(); see customizing hover tooltips.
Add a trendline with trendline="ols"
trendline="ols" fits a straight line by least squares, one per color group. trendline="lowess" draws a smoothed curve instead. Both need the statsmodels package (pip install statsmodels); without it you get ModuleNotFoundError: No module named 'statsmodels'.
fig = px.scatter(
trails, x="distance_km", y="climb_m", color="difficulty", trendline="ols",
category_orders={"difficulty": ["Easy", "Moderate", "Hard"]},
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)"},
width=800, height=450,
)
fig.show()
results = px.get_trendline_results(fig)
for row in results.itertuples():
print(row.difficulty, round(row.px_fit_results.params[1]), "m per km")

Easy 36 m per km
Moderate 71 m per km
Hard 98 m per km
The moderate and hard slopes land close to the 70 and 95 meters per kilometer used to make the data. The easy slope is flatter than its 45, because the random ±80 m added to every trail moves the fit more when the trails are short. px.get_trendline_results(fig) returns the fitted statsmodels results, so .params, .rsquared, and .summary() are all there. Hover over a trendline in the interactive chart to see its equation and R². Other options:
trendline_scope="overall"fits one line through all points instead of one per group.trendline_color_override="black"draws every trendline in one color.trendline="rolling"withtrendline_options=dict(window=5)draws a moving average;trendline="expanding"draws a running mean.trendline_options=dict(log_x=True)fits on a log scale.
Show the distributions on the margins
marginal_x= and marginal_y= add a small plot of each variable along the edges: "histogram", "box", "violin", or "rug":
fig = px.scatter(
trails, x="distance_km", y="climb_m", color="difficulty",
marginal_x="histogram", marginal_y="box",
category_orders={"difficulty": ["Easy", "Moderate", "Hard"]},
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)"},
width=800, height=550,
)
fig.show()

The box plots on the right show that hard trails' elevation gain barely overlaps the easy ones'. In Seaborn, the same layout is a joint plot.
Split into panels with facet_col
facet_col= draws one panel per category, with shared axes so the panels compare directly. facet_row= stacks them, and facet_col_wrap= wraps long rows:
fig = px.scatter(
trails, x="distance_km", y="climb_m", facet_col="difficulty", color="rating",
color_continuous_scale="Viridis",
category_orders={"difficulty": ["Easy", "Moderate", "Hard"]},
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)",
"rating": "Rating"},
width=900, height=400,
)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
fig.show()

The panel titles default to difficulty=Easy; the for_each_annotation line keeps only the part after the =. Plotly subplots covers grids of different chart types.
How do I label points with text?
text= writes a column's values next to each point. Label only a few points, or the chart gets crowded. Here only the five most-reviewed trails get a label:
top = trails.nlargest(5, "reviews")["trail"]
trails["label"] = trails["trail"].where(trails["trail"].isin(top), "")
fig = px.scatter(
trails, x="distance_km", y="climb_m", text="label",
labels={"distance_km": "Distance (km)", "climb_m": "Elevation gain (m)"},
width=800, height=450,
)
fig.update_traces(textposition="top center", marker=dict(color="#457b9d", size=8))
fig.show()

textposition takes values like "top center", "middle right", and "bottom left". For arrows and boxes, use fig.add_annotation(); see custom annotations in Plotly.
px.scatter options at a glance
| You want | Argument |
|---|---|
| Color by a column | color="col"; color_discrete_map={...} or color_continuous_scale="Viridis" |
| Marker size by a column | size="col", size_max=30 (largest marker, in pixels) |
| Marker shape by a column | symbol="col" |
| Transparent points | opacity=0.5 |
| Axis titles | labels={"col": "Title"} |
| Axis ranges or log scale | range_x=[0, 30], log_x=True |
| Error bars | error_y="col" |
| An animated scatter plot | animation_frame="year"; see animated bubble charts |
| Faster drawing for many points | render_mode="webgl" (automatic above 1,000 rows); see WebGL performance |
px.scatter vs go.Scatter
px.scatter builds a whole figure from a DataFrame in one call, with one trace per color group. go.Scatter is the trace it creates under the hood. Use go.Scatter with fig.add_trace() to add points to an existing figure, to mix them with other trace types, or when the data isn't in a DataFrame. A line chart is the same trace with mode="lines"; see Plotly line charts.
For a static scatter plot, Seaborn's scatterplot takes nearly the same arguments (hue instead of color), and Matplotlib's scatter gives full control of each marker.
Common problems
| Problem | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'statsmodels' |
trendline= needs statsmodels |
pip install statsmodels |
ValueError: Invalid element(s) received for the 'size' property |
The size column has negative values or NaN |
size=df["col"].fillna(0).clip(lower=0) |
| A numeric column gets a colorbar instead of a legend | Numbers use a continuous scale | color=df["col"].astype(str) |
| Legend order is random | Values are ordered by first appearance | category_orders={"col": [...]} |
| The chart doesn't appear | Renderer setup in Jupyter, VS Code, or a script | See Plotly renderers |
| Saving a PNG fails | fig.write_image() needs Kaleido |
See export static images with Kaleido |

