svgpower-curve
Power curve
How does power grow with sample size (or effect size), and where does it reach the target?
How to read it
- Read each curve as power at each sample size or effect size.
- Find where a curve crosses the target line.
- Read the dropped line for the sample size needed.
- Callout 1: Where this curve crosses the target.
- Callout 2: A smaller effect needs far more data.
- Callout 3: The target power.
Watch out
- Power from the effect you observed (“observed power”) adds nothing beyond the p-value. Choose an effect worth detecting.
Defaults
- Target power
- 0.8
- The chance of detecting the effect that you want the study to have, often 0.8 or 0.9.
- Range 0.5 to 0.99, step 0.05
- Log x axis
- Off
- Space the x axis by ratios, which suits values spanning orders of magnitude.
Pinned in the code
- Draws the engine's numbers as given (precomputed by the Python or R analysis); the chart computes nothing statistical.
- The crossing is interpolated linearly between the supplied points; the engine's solved n (rounded up) is the number to report.
- Demo: two-sample, two-sided z approximation Φ(d√(n/2) − z₁₋α/₂) + Φ(−d√(n/2) − z₁₋α/₂); the power module uses exact noncentral t.
# Power curve — Codesplash Chart Lab (recipe "power-curve")
# controls: target=0.8, xLog=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("power-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["effect"] = pd.Categorical(df["effect"].astype("string"), categories=["d = 0.3", "d = 0.5", "d = 0.8"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
X = "n per group"
P = "power"
S = "effect"
TARGET, XLOG = 0.8, False
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
d = df if name is None else df[df[S].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.axhline(TARGET, color="grey", linestyle="--", linewidth=1)
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
ax.plot(d[X], d[P], color=col, linewidth=2, label=name or P)
hit = d[d[P] >= TARGET]
if len(hit): # first x reaching the target
x0 = hit[X].iloc[0]
ax.plot([x0, x0], [0, TARGET], color=col, linestyle=":", linewidth=1)
ax.scatter([x0], [TARGET], color=col, zorder=3)
ax.annotate(f"{x0:g}", (x0, 0), textcoords="offset points", xytext=(3, 4), fontsize=8, color=col)
if XLOG:
ax.set_xscale("log")
ax.set_ylim(0, 1)
ax.set_xlabel(X)
ax.set_ylabel(P)
if S:
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads power-curve-demo.csv · app theme from the optional codesplash helper
# Power curve — Codesplash Chart Lab (recipe "power-curve")
# controls: target=0.8, xLog=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("power-curve-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["effect"] = pd.Categorical(df["effect"].astype("string"), categories=["d = 0.3", "d = 0.5", "d = 0.8"])
def levels_of(s):
"""Declared level order (categoricals), else order of first appearance."""
if isinstance(s.dtype, pd.CategoricalDtype):
return [v for v in s.cat.categories if (s == v).any()]
return list(dict.fromkeys(s.dropna().astype(str)))
X = "n per group"
P = "power"
S = "effect"
TARGET, XLOG = 0.8, False
groups = levels_of(df[S]) if S else [None]
series = []
for name in groups:
d = df if name is None else df[df[S].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values([X], kind="mergesort")))
fig = go.Figure()
fig.add_hline(y=TARGET, line=dict(color="grey", dash="dash", width=1))
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
fig.add_scatter(x=d[X], y=d[P], mode="lines", name=name or P, line=dict(color=col, width=2))
hit = d[d[P] >= TARGET]
if len(hit):
x0 = float(hit[X].iloc[0])
fig.add_scatter(x=[x0, x0], y=[0, TARGET], mode="lines+markers+text", line=dict(color=col, dash="dot", width=1),
marker=dict(size=[0, 8], color=col), text=[f"{x0:g}", ""], textposition="top right", showlegend=False)
fig.update_xaxes(type="log" if XLOG else "linear", title=X)
fig.update_yaxes(range=[0, 1], title=P)
fig.show()Needs pandas, numpy, plotly · reads power-curve-demo.csv · app theme from the optional codesplash helper
# Power curve — Codesplash Chart Lab (recipe "power-curve")
# controls: target=0.8, xLog=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("power-curve-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["effect"]] <- factor(df[["effect"]], levels = c("d = 0.3", "d = 0.5", "d = 0.8"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "n per group"
p_col <- "power"
s_col <- "effect"
target <- 0.8; x_log <- FALSE
d <- data.frame(x = df[[x_col]], p = df[[p_col]], g = if (is.null(s_col)) "" else factor(as.character(df[[s_col]]), levels = levels_of(df[[s_col]])))
d <- d[!is.na(d$x) & !is.na(d$p), ]
d <- d[order(d$g, d$x), ]
hit <- do.call(rbind, lapply(split(d, d$g, drop = TRUE), function(s) { h <- s[s$p >= target, ]; if (nrow(h)) h[1, ] else NULL })) # first x reaching the target
p <- ggplot(d, aes(x, p, colour = g)) +
geom_hline(yintercept = target, linetype = "dashed", colour = "grey60") +
geom_line(linewidth = 0.9) +
{ if (!is.null(hit)) list(geom_segment(data = hit, aes(xend = x, y = 0, yend = target), linetype = "dotted"), geom_point(data = transform(hit, p = target), size = 2.4),
geom_text(data = hit, aes(y = 0, label = format(x)), hjust = -0.2, vjust = -0.4, size = 3, show.legend = FALSE)) } +
{ if (x_log) scale_x_log10() } +
scale_colour_manual(values = cs_cat, guide = if (is.null(s_col)) "none" else "legend") +
coord_cartesian(ylim = c(0, 1)) + labs(x = x_col, y = p_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads power-curve-demo.csv · app theme from the optional codesplashr helper