canvasbrushablescatter-large
Large-n scatter (canvas)
What does the relationship look like across hundreds of thousands of rows?
How to read it
- Read the overall shape: too many points for individuals, so density is what you see.
- Use the colours to compare where groups sit.
- Look for sharp edges, which often mark caps or rounding in the data.
- Callout 1: Solid mass: lowering the opacity shows the density inside it.
- Callout 2: Sparse outer points: tails and possible errors.
Watch out
- Groups drawn last cover earlier ones, so a colour's area can mislead. Check with a hexbin.
Defaults
- Renderer
- Auto (canvas > 5,000)
- Draw as vector shapes or to a canvas; canvas stays fast with many points.
- Also: Canvas · SVG (capped at 20,000)
- Point size (px)
- 1.5
- The size of each point.
- Range 0.5 to 4, step 0.5
- Opacity
- 0.3
- How see-through points are; lower reveals density in crowded areas.
- Range 0.05 to 1, step 0.05
Pinned in the code
- Every row is drawn (no sampling) on canvas at 2× pixel density; overlapping marks build up density through the opacity.
- Colours come from the same theme tokens as the SVG renderer, resolved to rgb() for the canvas and repainted on theme change.
- Hover finds the nearest point within 8 px through a uniform-grid index over projected pixels (O(1) average).
- Static renders (exports, golden tests) omit the paint time from the caption so they stay deterministic.
# Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")
# controls: renderer=auto, size=1.5, opacity=0.3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
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"]
df = pd.read_csv("scatter-large-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["service"] = pd.Categorical(df["service"].astype("string"), categories=["Economy", "Comfort", "XL"])
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]
d = df.dropna(subset=["distance_km", "fare_usd"])
fig, ax = plt.subplots(figsize=(7, 4.5))
# every row is drawn; rasterized=True keeps vector exports small (the app paints to canvas)
for i, lv in enumerate(freq_levels(d["service"])):
m = d["service"].astype(str) == lv
ax.scatter(d["distance_km"][m], d["fare_usd"][m], s=2.25, alpha=0.3, color=PALETTE[i % len(PALETTE)], edgecolors="none", rasterized=True, label=lv)
ax.legend(title="service", fontsize=8, markerscale=4)
ax.set_xlabel("distance_km")
ax.set_ylabel("fare_usd")
ax.set_title(f"{len(d):,} points", fontsize=9, loc="left")
plt.show()Needs pandas, numpy, matplotlib · reads scatter-large-demo.csv · app theme from the optional codesplash helper
# Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")
# controls: renderer=auto, size=1.5, opacity=0.3
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
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
df = pd.read_csv("scatter-large-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["service"] = pd.Categorical(df["service"].astype("string"), categories=["Economy", "Comfort", "XL"])
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]
d = df.dropna(subset=["distance_km", "fare_usd"])
fig = go.Figure()
# Scattergl draws with WebGL, so hundreds of thousands of points stay interactive
for i, lv in enumerate(freq_levels(d["service"])):
m = d["service"].astype(str) == lv
fig.add_trace(go.Scattergl(x=d["distance_km"][m], y=d["fare_usd"][m], mode="markers", name=lv, marker=dict(color=PALETTE[i % len(PALETTE)], size=3, opacity=0.3)))
fig.update_layout(xaxis_title="distance_km", yaxis_title="fare_usd")
fig.show()Needs pandas, numpy, plotly · reads scatter-large-demo.csv · app theme from the optional codesplash helper
# Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")
# controls: renderer=auto, size=1.5, opacity=0.3
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))
df <- read.csv("scatter-large-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["service"]] <- factor(df[["service"]], levels = c("Economy", "Comfort", "XL"))
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[["service"]], "cs_declared") <- TRUE # stored level order
d <- df[!is.na(df[["distance_km"]]) & !is.na(df[["fare_usd"]]), , drop = FALSE]
# every row is drawn; shape 16 (solid, no outline) is the fastest point glyph on raster devices
p <- ggplot(d, aes(.data[["distance_km"]], .data[["fare_usd"]])) +
geom_point(aes(colour = .data[["service"]]), shape = 16, size = 0.525, alpha = 0.3) +
scale_colour_manual(values = cs_cat, name = "service") +
guides(colour = guide_legend(override.aes = list(size = 3, alpha = 1))) +
labs(x = "distance_km", y = "fare_usd", subtitle = paste(format(nrow(d), big.mark = ","), "points")) +
theme_cs
print(p)Needs ggplot2 · reads scatter-large-demo.csv · app theme from the optional codesplashr helper
-- Large-n scatter (canvas) — Codesplash Chart Lab (recipe "scatter-large")
-- controls: renderer=auto, size=1.5, opacity=0.3
-- density on a 400 × 300 pixel grid: what the canvas paint accumulates through opacity (per service)
WITH v AS (SELECT "distance_km"::DOUBLE AS x, "fare_usd"::DOUBLE AS y, "service" AS "service" FROM read_csv('scatter-large-demo.csv') WHERE "distance_km" IS NOT NULL AND "fare_usd" IS NOT NULL),
r AS (SELECT min(x) AS x0, max(x) AS x1, min(y) AS y0, max(y) AS y1 FROM v)
SELECT "service", least(floor((x - x0) / NULLIF(x1 - x0, 0) * 400), 399)::INTEGER AS px,
least(floor((y - y0) / NULLIF(y1 - y0, 0) * 300), 299)::INTEGER AS py,
count(*) AS n
FROM v, r
GROUP BY ALL
ORDER BY "service", py, px;Needs duckdb · reads scatter-large-demo.csv