svgbrushablescatter
Scatter plot
How do two numeric variables move together?
How to read it
- Read the overall direction: rising, falling or flat.
- Read how tightly the points follow the fit line, and whether the fit should be straight at all.
- Look for points far from the rest and for groups that behave differently.
- Callout 1: The fit line: the average trend, with its band.
- Callout 2: A cloud of one group: does the trend hold inside each group?
- Callout 3: Points far from the rest: check them before fitting.
Watch out
- A strong pattern does not show that one variable causes the other.
- A trend across groups can reverse inside them (Simpson's paradox).
Defaults
- Fit
- OLS + 95% CI
- Add a straight-line (OLS) or flexible (LOESS) trend line.
- Also: None · LOESS
- LOESS span
- 0.75
- The share of points in each local fit: smaller follows the data closely, larger is smoother.
- Range 0.2 to 1, step 0.05
- Point radius
- 3
- The size of each point.
- Range 1 to 6, step 0.5
- Opacity
- 0.7
- How see-through points are; lower reveals density in crowded areas.
- Range 0.1 to 1, step 0.1
- Renderer
- Auto (canvas > 5,000)
- Draw as vector shapes or to a canvas; canvas stays fast with many points.
- Also: SVG · Canvas
Pinned in the code
- OLS: ŷ = a + b·x by least squares; the band is the 95 % confidence interval of the mean, ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx).
- LOESS: local linear fits with tricube weights over the nearest span·n points (degree 1, no robustness iterations; R `loess(degree = 1, family = "gaussian")`).
- Rows with a missing x or y are dropped.
# Scatter plot — Codesplash Chart Lab (recipe "scatter")
# controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
from statsmodels.nonparametric.smoothers_lowess import lowess
import matplotlib.dates as mdates
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("scatter-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["Consumer", "SMB", "Enterprise"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def ols_band(x, y, level=0.95, points=60):
"""y = a + b·x with the pointwise CI of the mean: ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx)."""
n, mx = x.size, x.mean()
sxx = ((x - mx) ** 2).sum()
b = ((x - mx) * (y - y.mean())).sum() / sxx
a = y.mean() - b * mx
s = np.sqrt(((y - a - b * x) ** 2).sum() / (n - 2))
grid = np.linspace(x.min(), x.max(), points)
fit = a + b * grid
half = stats.t.ppf(1 - (1 - level) / 2, n - 2) * s * np.sqrt(1 / n + (grid - mx) ** 2 / sxx)
return grid, fit, fit - half, fit + half, a, b
def loess_curve(x, y, span, points=60):
"""Local linear fits, tricube weights over the floor(span·n) nearest points, no robustness
iterations — R loess(degree = 1, family = "gaussian", surface = "direct")."""
grid = np.linspace(x.min(), x.max(), points)
return grid, lowess(y, x, frac=span, it=0, delta=0.0, xvals=grid)
d = df.dropna(subset=["spend_k", "revenue_k"]) # rows with a missing x or y are dropped
xv = d["spend_k"].to_numpy(dtype=float)
yv = d["revenue_k"].to_numpy(dtype=float)
fig, ax = plt.subplots(figsize=(7, 4.5))
for i, lv in enumerate(freq_levels(d["segment"])):
m = (d["segment"].astype(str) == lv).to_numpy()
ax.scatter(xv[m], yv[m], color=PALETTE[i % len(PALETTE)], marker=SERIES_MARKERS[i % 8], label=lv, s=20.25, alpha=0.7, edgecolors="none") # marker shape per group, as in the app
ax.legend(title="segment", fontsize=8)
grid, fit, lo, hi, a, b = ols_band(xv, yv)
ax.fill_between(grid, lo, hi, color=REF, alpha=0.15, linewidth=0, label="95% CI")
ax.plot(grid, fit, color=REF, linewidth=2, label=f"OLS: y = {a:.3g} + {b:.3g}·x")
ax.set_xlabel("spend_k")
ax.set_ylabel("revenue_k")
plt.show()Needs pandas, numpy, matplotlib, scipy, statsmodels · reads scatter-demo.csv · app theme from the optional codesplash helper
# Scatter plot — Codesplash Chart Lab (recipe "scatter")
# controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
from statsmodels.nonparametric.smoothers_lowess import lowess
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
df = pd.read_csv("scatter-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["segment"] = pd.Categorical(df["segment"].astype("string"), categories=["Consumer", "SMB", "Enterprise"])
_tokens = cs.palette(dark=False) if cs else {}
SEQ = _tokens.get("sequential", ["#eff6fd", "#1a469d"]) # sequential ramp (low → high)
DIV = _tokens.get("diverging", ["#c13e2e", "#f3f5f8", "#0859ac"]) # negative, midpoint, positive
REF = _tokens.get("reference", "#4e5661")
GREY = _tokens.get("dim", "#ced1d6")
def freq_levels(s, k=8):
"""Declared level order when the column is categorical, else by descending count (ties A→Z)."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [str(v) for v in s.cat.categories][:k]
vc = s.dropna().astype(str).value_counts()
return sorted(vc.index, key=lambda v: (-vc[v], v))[:k]
def ols_band(x, y, level=0.95, points=60):
"""y = a + b·x with the pointwise CI of the mean: ŷ ± t(0.975, n−2)·s·√(1/n + (x−x̄)²/Sxx)."""
n, mx = x.size, x.mean()
sxx = ((x - mx) ** 2).sum()
b = ((x - mx) * (y - y.mean())).sum() / sxx
a = y.mean() - b * mx
s = np.sqrt(((y - a - b * x) ** 2).sum() / (n - 2))
grid = np.linspace(x.min(), x.max(), points)
fit = a + b * grid
half = stats.t.ppf(1 - (1 - level) / 2, n - 2) * s * np.sqrt(1 / n + (grid - mx) ** 2 / sxx)
return grid, fit, fit - half, fit + half, a, b
def loess_curve(x, y, span, points=60):
"""Local linear fits, tricube weights over the floor(span·n) nearest points, no robustness
iterations — R loess(degree = 1, family = "gaussian", surface = "direct")."""
grid = np.linspace(x.min(), x.max(), points)
return grid, lowess(y, x, frac=span, it=0, delta=0.0, xvals=grid)
d = df.dropna(subset=["spend_k", "revenue_k"])
xv = d["spend_k"].to_numpy(dtype=float)
yv = d["revenue_k"].to_numpy(dtype=float)
fig = go.Figure()
for i, lv in enumerate(freq_levels(d["segment"])):
m = (d["segment"].astype(str) == lv).to_numpy()
fig.add_scatter(x=d["spend_k"][m], y=yv[m], mode="markers", name=lv, marker=dict(color=PALETTE[i % len(PALETTE)], symbol=SERIES_MARKERS[i % 8], size=6, opacity=0.7)) # marker shape per group, as in the app
grid, fit, lo, hi, a, b = ols_band(xv, yv)
gx = grid
fig.add_scatter(x=np.r_[gx, gx[::-1]], y=np.r_[hi, lo[::-1]], fill="toself", fillcolor="rgba(78,86,97,0.15)", line_width=0, name="95% CI", hoverinfo="skip")
fig.add_scatter(x=gx, y=fit, mode="lines", line=dict(color=REF, width=2), name="OLS")
fig.update_layout(xaxis_title="spend_k", yaxis_title="revenue_k")
fig.show()Needs pandas, numpy, plotly, scipy, statsmodels · reads scatter-demo.csv · app theme from the optional codesplash helper
# Scatter plot — Codesplash Chart Lab (recipe "scatter")
# controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("scatter-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["segment"]] <- factor(df[["segment"]], levels = c("Consumer", "SMB", "Enterprise"))
tok <- if (has_cs) codesplashr::cs_palette(dark = FALSE) else list()
seq_ramp <- if (is.null(tok$sequential)) c("#eff6fd", "#1a469d") else tok$sequential # low → high
div_ramp <- if (is.null(tok$diverging)) c("#c13e2e", "#f3f5f8", "#0859ac") else tok$diverging # −, 0, +
ref_col <- if (is.null(tok$reference)) "#4e5661" else tok$reference
grey_col <- if (is.null(tok$dim)) "#ced1d6" else tok$dim
freq_levels <- function(v, k = 8) {
# declared level order for factors with stored levels, else descending count (ties A→Z)
if (is.factor(v) && !is.null(attr(v, "cs_declared"))) return(utils::head(levels(v), k))
v <- as.character(v[!is.na(v)])
tab <- table(v)
utils::head(names(tab)[order(-as.vector(tab), names(tab))], k)
}
attr(df[["segment"]], "cs_declared") <- TRUE # stored level order
d <- df[!is.na(df[["spend_k"]]) & !is.na(df[["revenue_k"]]), , drop = FALSE] # rows with a missing x or y are dropped
p <- ggplot(d, aes(x = .data[["spend_k"]], y = .data[["revenue_k"]])) +
geom_point(aes(colour = .data[["segment"]], shape = .data[["segment"]]), size = 1.8, alpha = 0.7) +
scale_colour_manual(values = cs_cat, name = "segment") + scale_shape_manual(values = cs_shapes, name = "segment") + # shape per group, as in the app
# one overall fit (colour only maps the points), 95% CI of the mean
geom_smooth(method = "lm", formula = y ~ x, level = 0.95, colour = ref_col, fill = ref_col, alpha = 0.15) +
labs(x = "spend_k", y = "revenue_k") +
theme_cs
print(p)Needs ggplot2 · reads scatter-demo.csv · app theme from the optional codesplashr helper
-- Scatter plot — Codesplash Chart Lab (recipe "scatter")
-- controls: fit=ols, span=0.75, size=3, opacity=0.7, renderer=auto
-- OLS fit y = a + b·x over rows with both values (the band needs t(0.975, n − 2) on the client)
-- the chart fits all rows (group NULL); per-segment fits are listed for comparison
WITH v AS (SELECT "spend_k"::DOUBLE AS x, "revenue_k"::DOUBLE AS y, "segment"::VARCHAR AS grp FROM read_csv('scatter-demo.csv') WHERE "spend_k" IS NOT NULL AND "revenue_k" IS NOT NULL)
SELECT grp AS "segment", regr_count(y, x) AS n,
regr_intercept(y, x) AS intercept,
regr_slope(y, x) AS slope,
regr_r2(y, x) AS r2,
sqrt(regr_syy(y, x) * (1 - regr_r2(y, x)) / (regr_count(y, x) - 2)) AS sigma,
sqrt(regr_syy(y, x) * (1 - regr_r2(y, x)) / (regr_count(y, x) - 2)) / sqrt(regr_sxx(y, x)) AS se_slope,
avg(x) AS mean_x,
regr_sxx(y, x) AS sxx
FROM v
GROUP BY GROUPING SETS ((), (grp))
ORDER BY grp NULLS FIRST;Needs duckdb · reads scatter-demo.csv