Interactive Scatter Plots
When to reach for a scatter plot
A scatter plot answers “how do these two numeric variables relate?” Each point is one row of data, positioned by two measurements at once. Add colorcolor for a third variable (a category) and sizesize for a fourth (a number) — a scatter plot can honestly encode more information per point than almost any other chart type.
Basic scatter
import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"hours": [1, 2, 3, 4, 5, 6, 7, 2, 4, 6],
"score": [50, 55, 65, 70, 75, 78, 85, 52, 69, 77],
"group": ["A", "A", "A", "A", "A", "A", "A", "B", "B", "B"],
})
fig = px.scatter(df, x="hours", y="score", color="group", title="Hours vs score")
fig.show()import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"hours": [1, 2, 3, 4, 5, 6, 7, 2, 4, 6],
"score": [50, 55, 65, 70, 75, 78, 85, 52, 69, 77],
"group": ["A", "A", "A", "A", "A", "A", "A", "B", "B", "B"],
})
fig = px.scatter(df, x="hours", y="score", color="group", title="Hours vs score")
fig.show()Every point is hoverable by default — Plotly shows xx, yy, and colorcolor for whichever point the cursor is nearest, with zero extra code.
Add trend line
import plotly.express as px
fig = px.scatter(df, x="hours", y="score", color="group", trendline="ols", title="Trend line")
fig.show()import plotly.express as px
fig = px.scatter(df, x="hours", y="score", color="group", trendline="ols", title="Trend line")
fig.show()trendline="ols"trendline="ols" fits an ordinary-least-squares regression line per color group and draws it on top — a quick way to see if a relationship looks roughly linear (requires statsmodelsstatsmodels installed).
Tips
- Use
hover_data=[...]hover_data=[...]to show more context (e.g. a name or ID column) in the tooltip. - Trend lines can be sensitive to outliers — a single extreme point can tilt the whole fitted line.
- If points overlap heavily, lower
opacityopacityor switch to a 2D density/contour plot.
flowchart LR A["One data row"] --> B["x position
(variable 1)"] A --> C["y position
(variable 2)"] A --> D["color
(category, optional)"] A --> E["size
(magnitude, optional)"] B & C & D & E --> F["One point,
hoverable for exact values"]
Next
Continue to: Bubble Charts to add a size dimension to your scatter plots.
🧪 Try It Yourself
Exercise 1 – Plot Two Variables
Exercise 2 – Color by Group
Exercise 3 – Add a Trend Line
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
