svgcontour-grid
Contour grid
How does a quantity change over two inputs — where is it zero, where is it highest?
How to read it
- Read colour as the value across two inputs.
- Follow the bold zero contour: where the conclusion flips.
- Check the labelled points: benchmarks for how strong an unmeasured confounder would be.
- Callout 1: Stronger red: a larger bias.
- Callout 2: Benchmark points.
- Callout 3: Colour scale.
Watch out
- Benchmarks assume unmeasured confounders resemble measured ones, which may not hold.
Defaults
- Contour levels
- 10
- How many contour bands to draw.
- Range 3 to 30, step 1
- Emphasize the zero contour
- Off
- Draw the line where the value is zero in bold: where the conclusion flips.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- The grid rows form a lattice over their distinct x and y values; bands are marching squares (d3-contour) at k equally spaced levels strictly between the minimum and maximum, plus 0 when 'zero contour' is on.
- A diverging palette is used when the values span zero (blue above, red below), else a sequential one.
- Sensemakr: x = partial R² of the confounder with the treatment, y = with the outcome, z = adjusted estimate; the dashed zero contour is where the effect would vanish, and points are the benchmark confounders.
# Contour grid — Codesplash Chart Lab (recipe "contour-grid")
# controls: levels=10, zero_line=false
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("contour-grid-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["grid", "point"])
X = "partial R² of confounder with treatment"
Y = "partial R² of confounder with outcome"
Z = "adjusted estimate"
KIND = "kind"
LABEL = "label"
LEVELS, ZERO = 10, False
grid = df[df[KIND].astype(str) != "point"] if KIND else df
wide = grid.pivot_table(index=Y, columns=X, values=Z) # lattice over the distinct x and y values
zmin, zmax = np.nanmin(wide.values), np.nanmax(wide.values)
levels = np.linspace(zmin, zmax, LEVELS + 2)
cmap = "RdBu" if zmin < 0 < zmax else "Blues"
fig, ax = plt.subplots(figsize=(8, 4.5))
norm = plt.Normalize(-max(abs(zmin), abs(zmax)), max(abs(zmin), abs(zmax))) if zmin < 0 < zmax else None
cs_ = ax.contourf(wide.columns, wide.index, wide.values, levels=levels, cmap=cmap, norm=norm)
fig.colorbar(cs_, ax=ax, label=Z)
if ZERO and zmin < 0 < zmax:
ax.contour(wide.columns, wide.index, wide.values, levels=[0], colors="black", linestyles="--", linewidths=1.6)
if KIND:
pts = df[df[KIND].astype(str) == "point"]
ax.scatter(pts[X], pts[Y], marker="D", color="black", s=24)
for _, r in pts.iterrows():
ax.annotate(f"{r[LABEL]}" if LABEL else "", (r[X], r[Y]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
ax.set_xlabel(X)
ax.set_ylabel(Y)
plt.show()Needs pandas, numpy, matplotlib · reads contour-grid-demo.csv · app theme from the optional codesplash helper
# Contour grid — Codesplash Chart Lab (recipe "contour-grid")
# controls: levels=10, zero_line=false
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("contour-grid-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["grid", "point"])
X = "partial R² of confounder with treatment"
Y = "partial R² of confounder with outcome"
Z = "adjusted estimate"
KIND = "kind"
LABEL = "label"
LEVELS = 10
grid = df[df[KIND].astype(str) != "point"] if KIND else df
wide = grid.pivot_table(index=Y, columns=X, values=Z)
zmin, zmax = np.nanmin(wide.values), np.nanmax(wide.values)
fig = go.Figure(go.Contour(x=wide.columns, y=wide.index, z=wide.values, ncontours=LEVELS + 2, colorscale="RdBu" if zmin < 0 < zmax else "Blues",
zmid=0 if zmin < 0 < zmax else None, colorbar_title=Z))
if KIND:
pts = df[df[KIND].astype(str) == "point"]
fig.add_scatter(x=pts[X], y=pts[Y], mode="markers+text", text=pts[LABEL] if LABEL else None, textposition="middle right",
marker=dict(symbol="diamond", color="black", size=8), showlegend=False)
fig.update_layout(xaxis_title=X, yaxis_title=Y)
fig.show()Needs pandas, numpy, plotly · reads contour-grid-demo.csv · app theme from the optional codesplash helper
# Contour grid — Codesplash Chart Lab (recipe "contour-grid")
# controls: levels=10, zero_line=false
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("contour-grid-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["kind"]] <- factor(df[["kind"]], levels = c("grid", "point"))
df[["label"]] <- factor(df[["label"]])
x_col <- "partial R² of confounder with treatment"
y_col <- "partial R² of confounder with outcome"
z_col <- "adjusted estimate"
kind_col <- "kind"
label_col <- "label"
levels_n <- 10; zero_line <- FALSE
d <- data.frame(x = df[[x_col]], y = df[[y_col]], z = df[[z_col]], kind = if (is.null(kind_col)) "grid" else as.character(df[[kind_col]]))
grid <- d[d$kind != "point" & !is.na(d$z), ]
pts <- d[d$kind == "point", ]
pts$label <- if (is.null(label_col)) "" else as.character(df[[label_col]])[d$kind == "point"]
diverging <- min(grid$z) < 0 && max(grid$z) > 0
p <- ggplot(grid, aes(x, y, z = z)) + geom_contour_filled(bins = levels_n + 1) +
{ if (zero_line && diverging) geom_contour(breaks = 0, colour = "black", linetype = "dashed", linewidth = 0.8) } +
geom_point(data = pts, aes(x, y), inherit.aes = FALSE, shape = 18, size = 3) +
geom_text(data = pts, aes(x, y, label = label), inherit.aes = FALSE, hjust = -0.15, size = 3) +
scale_fill_manual(values = if (diverging) grDevices::hcl.colors(levels_n + 1, "RdBu") else grDevices::hcl.colors(levels_n + 1, "Blues", rev = TRUE)) +
labs(x = x_col, y = y_col, fill = z_col) + theme_cs
print(p)Needs ggplot2 · reads contour-grid-demo.csv · app theme from the optional codesplashr helper