svgposterior-density
Posterior densities
Given the data, where does each arm's true rate (or the lift) probably lie, and how much do the posteriors overlap?
How to read it
- Read each curve as where that arm's true rate probably lies.
- Read the bars below for the 95% highest-density intervals.
- Less overlap means more certainty that the arms differ.
- Callout 1: Arm A's most plausible rates.
- Callout 2: Arm B's.
- Callout 3: The intervals under the axis.
Watch out
- The result depends on the prior, though less so with plenty of data.
Defaults
- ROPE lower (equal bounds = none)
- 0
- The lower end of the range of effects you would call practically zero.
- Range -1,000,000,000 to 1,000,000,000, step 0.001
- ROPE upper
- 0
- The upper end of the range of effects you would call practically zero.
- Range -1,000,000,000 to 1,000,000,000, step 0.001
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- The engine evaluates each posterior on a grid; the chart integrates the grid by the trapezoid rule for the mean and takes the narrowest set of grid points holding 95% of the mass as the HDI (exact for unimodal posteriors up to the grid spacing).
- Values below 0.5 on a [0, 1] scale are shown as percentages (conversion rates).
- P(B > A) and expected loss come from the engine's joint posterior draws, not from these marginal curves.
# Posterior densities — Codesplash Chart Lab (recipe "posterior-density")
# controls: rope_low=0, rope_high=0
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("posterior-density-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["A (control)", "B (new checkout)"])
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 = "conversion rate"
D = "posterior density"
ARM = "arm"
ROPE = (0, 0)
groups = levels_of(df[ARM]) if ARM else [None]
series = []
for name in groups:
d = df if name is None else df[df[ARM].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig, ax = plt.subplots(figsize=(8, 4.5))
if None not in ROPE and ROPE[1] > ROPE[0]:
ax.axvspan(*ROPE, color="grey", alpha=0.12, lw=0, label="ROPE")
for i, (name, d) in enumerate(series):
col = PALETTE[i % len(PALETTE)]
ax.fill_between(d[X], d[D], color=col, alpha=0.2, lw=0)
ax.plot(d[X], d[D], color=col, linewidth=1.8, label=name or D)
ax.set_xlabel(X)
ax.set_ylabel("density")
ax.set_ylim(bottom=0)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads posterior-density-demo.csv · app theme from the optional codesplash helper
# Posterior densities — Codesplash Chart Lab (recipe "posterior-density")
# controls: rope_low=0, rope_high=0
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("posterior-density-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["A (control)", "B (new checkout)"])
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 = "conversion rate"
D = "posterior density"
ARM = "arm"
groups = levels_of(df[ARM]) if ARM else [None]
series = []
for name in groups:
d = df if name is None else df[df[ARM].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[X]).sort_values(X)))
fig = go.Figure()
for i, (name, d) in enumerate(series):
fig.add_scatter(x=d[X], y=d[D], mode="lines", fill="tozeroy", name=name or D, line=dict(color=PALETTE[i % len(PALETTE)], width=2))
fig.update_layout(xaxis_title=X, yaxis_title="density")
fig.show()Needs pandas, numpy, plotly · reads posterior-density-demo.csv · app theme from the optional codesplash helper
# Posterior densities — Codesplash Chart Lab (recipe "posterior-density")
# controls: rope_low=0, rope_high=0
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("posterior-density-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("A (control)", "B (new checkout)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
x_col <- "conversion rate"
d_col <- "posterior density"
arm_col <- "arm"
rope <- c(0, 0)
d <- data.frame(x = df[[x_col]], dens = df[[d_col]], arm = if (is.null(arm_col)) "posterior" else factor(as.character(df[[arm_col]]), levels = levels_of(df[[arm_col]])))
p <- ggplot(d, aes(x, dens, colour = arm, fill = arm)) +
{ if (length(rope) == 2 && rope[2] > rope[1]) annotate("rect", xmin = rope[1], xmax = rope[2], ymin = -Inf, ymax = Inf, fill = "grey50", alpha = 0.12) } +
geom_area(alpha = 0.2, position = "identity") + geom_line(linewidth = 0.9) +
scale_colour_manual(values = cs_cat) + scale_fill_manual(values = cs_cat) +
labs(x = x_col, y = "density", colour = NULL, fill = NULL) + theme_cs
print(p)Needs ggplot2 · reads posterior-density-demo.csv · app theme from the optional codesplashr helper