# Plotly Scatter Plot: px.scatter() With Color, Size, Hover, and Trendlines

> Make a Plotly scatter plot with px.scatter(df, x="a", y="b", color="group", size="n", hover_name="name"). Covers colors, hover_data, trendline="ols", marginal plots, facets, and text labels.

Source: https://www.pythoncharts.com/plotly/plotly-scatter-plot/ | Published: 2026-12-05 | Author: Alex Scott | Category: Plotly | Tags: plotly, plotly express, scatter, scatter plot, trendline, hover

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:

```python
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()
```

![Plotly bubble scatter plot of 90 hiking trails, distance against elevation gain, colored Easy, Moderate, and Hard and sized by review count: easy trails are short and flat, hard trails are longer and climb about twice as much per kilometer](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-quick-example.png)

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:

```python
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()
```

![Plotly scatter plot of trail distance against elevation gain with points colored by rating on a Viridis colorscale from 3 to 5, shown in a colorbar on the right](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-continuous-color.png)

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:

```python
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()
```

![Plotly scatter plot of trails colored by difficulty whose tooltips show the trail name, distance, elevation gain, rating, and review count](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-hover.png)

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](https://www.pythoncharts.com/plotly/plotly-customize-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'`.

```python
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")
```

![Plotly scatter plot of trails with one straight OLS trendline per difficulty, where the Hard line is the steepest, Moderate in the middle, and Easy the flattest](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-trendline.png)

```text
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"` with `trendline_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"`:

```python
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()
```

![Plotly scatter plot of trails with overlaid histograms of distance along the top and box plots of elevation gain for each difficulty along the right side](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-marginal.png)

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](https://www.pythoncharts.com/seaborn/seaborn-jointplot-bivariate-distributions/).

## 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:

```python
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()
```

![Three Plotly scatter panels side by side for Easy, Moderate, and Hard trails, sharing the same axes and colored by rating](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-facets.png)

The panel titles default to `difficulty=Easy`; the `for_each_annotation` line keeps only the part after the `=`. [Plotly subplots](https://www.pythoncharts.com/plotly/plotly-make-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:

```python
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()
```

![Plotly scatter plot of trails in a single blue with the names of the five most-reviewed trails written above their points](https://www.pythoncharts.com/plotly/plotly-scatter-plot/images/plotly-scatter-text-labels.png)

`textposition` takes values like `"top center"`, `"middle right"`, and `"bottom left"`. For arrows and boxes, use `fig.add_annotation()`; see [custom annotations in Plotly](https://www.pythoncharts.com/plotly/plotly-add-custom-annotations/).

## `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](https://www.pythoncharts.com/plotly/animated-bubble-charts/) |
| Faster drawing for many points | `render_mode="webgl"` (automatic above 1,000 rows); see [WebGL performance](https://www.pythoncharts.com/plotly/plotly-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](https://www.pythoncharts.com/plotly/plotly-express-line-charts/).

For a static scatter plot, [Seaborn's `scatterplot`](https://www.pythoncharts.com/seaborn/seaborn-scatterplot/) takes nearly the same arguments (`hue` instead of `color`), and [Matplotlib's `scatter`](https://www.pythoncharts.com/matplotlib/matplotlib-scatterplot/) 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](https://www.pythoncharts.com/plotly/plotly-not-showing-renderers/) |
| Saving a PNG fails | `fig.write_image()` needs Kaleido | See [export static images with Kaleido](https://www.pythoncharts.com/plotly/plotly-export-static-images-with-kaleido/) |

## Similar Topics

- [Seaborn Scatter Plot: sns.scatterplot() with hue, size, and style](https://www.pythoncharts.com/seaborn/seaborn-scatterplot/)
- [Customize Hover Tooltips in Plotly](https://www.pythoncharts.com/plotly/plotly-customize-hover-tooltips/)
- [Animated Bubble Charts in Plotly](https://www.pythoncharts.com/plotly/animated-bubble-charts/)
