svgboxcox-profile
Box–Cox profile
Which power transformation would make this outcome behave best?
How to read it
- Find the peak: the λ that makes the transformed outcome fit best.
- Read the shaded interval: any λ in it fits about as well.
- Prefer a round value inside the interval: 0 (log), 0.5 (square root) or 1 (no change).
- Callout 1: The best λ, with its interval shaded.
- Callout 2: The dashed line: the interval's cutoff.
- Callout 3: λ = 1 means no transformation.
Watch out
- It targets normal residuals with equal spread, not interpretation. A transformed outcome changes what the coefficients mean.
Defaults
- Interval level
- 0.95
- How often intervals built this way contain the true value, over repeated samples.
- Range 0.5 to 0.99, step 0.01
Demo data
- Skew of the demo data
- 0.7
- The log-normal σ behind the demo: more skew moves the best λ towards the log.
- Range 0.1 to 1.5, step 0.1
Pinned in the code
- As MASS::boxcox: y is divided by its geometric mean, then log-likelihood = −n/2 · log RSS of the transformed y.
- The interval is where the curve stays within χ²₁(level)/2 of its maximum, by linear interpolation on the λ grid.
# Box–Cox profile — Codesplash Chart Lab (recipe "boxcox-profile")
# controls: level=0.95
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
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("boxcox-profile-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
L = "λ"
LL = "log-likelihood"
d = df.dropna(subset=[L, LL]).sort_values(L)
lam, ll = d[L].to_numpy(float), d[LL].to_numpy(float)
best = int(np.argmax(ll))
cut = ll[best] - stats.chi2.ppf(0.95, 1) / 2 # interval: within χ²₁/2 of the maximum
inside = np.flatnonzero(ll >= cut)
lo = np.interp(cut, ll[: inside[0] + 1], lam[: inside[0] + 1]) if inside[0] > 0 else np.nan
hi = np.interp(cut, ll[inside[-1] :][::-1], lam[inside[-1] :][::-1]) if inside[-1] < len(ll) - 1 else np.nan
fig, ax = plt.subplots(figsize=(7, 4))
if np.isfinite(lo) and np.isfinite(hi):
ax.axvspan(lo, hi, color=PALETTE[0], alpha=0.1, label=f"interval [{lo:.2f}, {hi:.2f}]")
ax.plot(lam, ll, color=PALETTE[0], linewidth=2)
ax.scatter([lam[best]], [ll[best]], s=40, color=PALETTE[0], zorder=3, label=f"best λ {lam[best]:.2f}")
ax.axhline(cut, color=REF, linestyle="--", linewidth=1)
for v, t in ((0, "log"), (1, "no change")):
if lam[0] <= v <= lam[-1]:
ax.axvline(v, color=REF, linestyle=":", linewidth=0.8)
ax.annotate(t, (v, ll.max()), fontsize=8, xytext=(3, 0), textcoords="offset points")
ax.set_xlabel("λ")
ax.set_ylabel("log-likelihood")
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib, scipy · reads boxcox-profile-demo.csv · app theme from the optional codesplash helper
# Box–Cox profile — Codesplash Chart Lab (recipe "boxcox-profile")
# controls: level=0.95
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from scipy import stats
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("boxcox-profile-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
_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")
L = "λ"
LL = "log-likelihood"
d = df.dropna(subset=[L, LL]).sort_values(L)
lam, ll = d[L].to_numpy(float), d[LL].to_numpy(float)
best = int(np.argmax(ll))
cut = ll[best] - stats.chi2.ppf(0.95, 1) / 2 # interval: within χ²₁/2 of the maximum
inside = np.flatnonzero(ll >= cut)
lo = np.interp(cut, ll[: inside[0] + 1], lam[: inside[0] + 1]) if inside[0] > 0 else np.nan
hi = np.interp(cut, ll[inside[-1] :][::-1], lam[inside[-1] :][::-1]) if inside[-1] < len(ll) - 1 else np.nan
fig = go.Figure()
fig.add_scatter(x=lam, y=ll, mode="lines", line=dict(color=PALETTE[0], width=2.5), name="profile")
fig.add_scatter(x=[lam[best]], y=[ll[best]], mode="markers", marker=dict(color=PALETTE[0], size=10), name=f"best λ {lam[best]:.2f}")
fig.add_hline(y=cut, line_dash="dash", line_color=REF)
if np.isfinite(lo) and np.isfinite(hi):
fig.add_vrect(x0=lo, x1=hi, fillcolor=PALETTE[0], opacity=0.1, line_width=0)
fig.update_layout(xaxis_title="λ", yaxis_title="log-likelihood")
fig.show()Needs pandas, numpy, plotly, scipy · reads boxcox-profile-demo.csv · app theme from the optional codesplash helper
# Box–Cox profile — Codesplash Chart Lab (recipe "boxcox-profile")
# controls: level=0.95
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("boxcox-profile-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
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
L <- "λ"
LL <- "log-likelihood"
d <- data.frame(l = df[[L]], ll = df[[LL]])
d <- d[is.finite(d$l) & is.finite(d$ll), ]
d <- d[order(d$l), ]
best <- which.max(d$ll)
cut <- d$ll[best] - qchisq(0.95, 1) / 2 # interval: within χ²₁/2 of the maximum
inside <- which(d$ll >= cut)
lo <- if (inside[1] > 1) approx(d$ll[(inside[1] - 1):inside[1]], d$l[(inside[1] - 1):inside[1]], cut)$y else NA
last <- inside[length(inside)]
hi <- if (last < nrow(d)) approx(d$ll[last:(last + 1)], d$l[last:(last + 1)], cut)$y else NA
p <- ggplot(d, aes(l, ll)) +
(if (is.finite(lo) && is.finite(hi)) annotate("rect", xmin = lo, xmax = hi, ymin = -Inf, ymax = Inf, fill = cs_cat[[1]], alpha = 0.1)) +
geom_hline(yintercept = cut, colour = ref_col, linetype = "dashed") +
geom_vline(xintercept = c(0, 1), colour = ref_col, linetype = "dotted") +
geom_line(colour = cs_cat[[1]], linewidth = 0.9) +
annotate("point", x = d$l[best], y = d$ll[best], colour = cs_cat[[1]], size = 2.5) +
labs(x = "λ", y = "log-likelihood", subtitle = sprintf("best λ %.2f", d$l[best])) + theme_cs
print(p)Needs ggplot2 · reads boxcox-profile-demo.csv · app theme from the optional codesplashr helper