svgpredicted-distributions
Predicted distributions
What does a probabilistic model predict for individual rows, and how likely was what actually happened?
How to read it
- Read each curve as the full distribution the model predicts for one row; its peak is the most likely value.
- Read a curve's width as the model's uncertainty for that row: narrow is confident.
- Follow the dashed line up from the actual value: its height is the likelihood the model gave to what happened.
- Callout 1: A narrow, tall curve: a confident prediction.
- Callout 2: A wide, low curve: an uncertain one.
- Callout 3: Dashed line: the density at the actual value.
Watch out
- Five rows are an illustration, not evidence; check 90% coverage and the NLL or CRPS across held-out rows.
- The chosen distribution shapes every curve. A Normal can put weight on impossible negative values.
Defaults
- Counts (stems)
- Off
- Draw probability masses as stems, for a count distribution such as the Poisson.
Pinned in the code
- Draws the numbers the learner published (training history, member predictions, predicted densities); the chart computes nothing statistical.
- Curves are evaluated by the learner on a grid of target values (81 points spanning ±3.5 SD of the shown rows, or every count for the Poisson).
- A tall curve is a confident prediction; the dashed line's height is the likelihood of the actual value — the quantity the log score rewards.
# Predicted distributions — Codesplash Chart Lab (recipe "predicted-distributions")
# controls: discrete=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"]
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["-", (0, (6, 3)), (0, (1.5, 2.5)), (0, (8, 3, 2, 3)), (0, (12, 4)), (0, (3, 3)), (0, (8, 2, 2, 2, 2, 2)), (0, (1.5, 5))]
SERIES_MARKERS = ["o", "s", "^", "D", "P", "*", "2", "v"]
df = pd.read_csv("predicted-distributions-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["row"] = pd.Categorical(df["row"].astype("string"), categories=["row 12 (actual 25.1)", "row 47 (actual 19.3)", "row 3 (actual 50.6)", "row 88 (actual 88.2)", "row 61 (actual 72.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 = "ozone (ppb)"
D = "density"
S = "row"
A = "actual"
DISCRETE = False
series = levels_of(df[S])
fig, ax = plt.subplots(figsize=(7, 4.2))
for i, s in enumerate(series):
d = df[df[S].astype(str) == s].sort_values(X)
colour = PALETTE[i % len(PALETTE)]
if DISCRETE:
off = (i - (len(series) - 1) / 2) * 0.14 # side by side at each count
ax.vlines(d[X] + off, 0, d[D], color=colour, linewidth=1.2)
ax.plot(d[X] + off, d[D], SERIES_MARKERS[i % 8], color=colour, markersize=3, label=s) # marker shape per row, as in the app
else:
ax.fill_between(d[X], 0, d[D], color=colour, alpha=0.08, linewidth=0)
ax.plot(d[X], d[D], color=colour, linewidth=1.6, linestyle=SERIES_DASHES[i % 8], label=s) # dash per row, as in the app
if A and d[A].notna().any():
a = float(d[A].dropna().iloc[0])
top = float(np.interp(a, d[X], d[D])) if not DISCRETE else float(d[D].max()) * 0.08
ax.vlines(a, 0, top, color=colour, linestyle="--", linewidth=1.1) # height = likelihood of the actual
if not DISCRETE:
ax.plot([a], [top], SERIES_MARKERS[i % 8], markerfacecolor="white", markeredgecolor=colour, markersize=6) # the row's marker at the actual
ax.set_ylim(bottom=0)
ax.set_xlabel(X)
ax.set_ylabel(D)
ax.legend(frameon=False, fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads predicted-distributions-demo.csv · app theme from the optional codesplash helper
# Predicted distributions — Codesplash Chart Lab (recipe "predicted-distributions")
# controls: discrete=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
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
SERIES_DASHES = ["solid", "6px,3px", "1.5px,2.5px", "8px,3px,2px,3px", "12px,4px", "3px,3px", "8px,2px,2px,2px,2px,2px", "1.5px,5px"]
SERIES_MARKERS = ["circle", "square", "triangle-up", "diamond", "cross", "star", "y-up", "triangle-down"]
SERIES_HATCHES = ["", "/", ".", "\\", "-", "x", "|", "+"]
HATCH_INK = "rgba(255,255,255,0.5)" # stripes let the chart surface show through
df = pd.read_csv("predicted-distributions-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["row"] = pd.Categorical(df["row"].astype("string"), categories=["row 12 (actual 25.1)", "row 47 (actual 19.3)", "row 3 (actual 50.6)", "row 88 (actual 88.2)", "row 61 (actual 72.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 = "ozone (ppb)"
D = "density"
S = "row"
A = "actual"
DISCRETE = False
series = levels_of(df[S])
fig = go.Figure()
for i, s in enumerate(series):
d = df[df[S].astype(str) == s].sort_values(X)
colour = PALETTE[i % len(PALETTE)]
if DISCRETE:
fig.add_trace(go.Bar(x=d[X], y=d[D], name=s, marker=dict(color=colour, pattern=dict(shape=SERIES_HATCHES[i % 8], fgcolor=HATCH_INK, fillmode="overlay")))) # texture per row
else:
fig.add_trace(go.Scatter(x=d[X], y=d[D], mode="lines", name=s, line=dict(color=colour, width=2, dash=SERIES_DASHES[i % 8]))) # dash per row, as in the app
if A and d[A].notna().any():
a = float(d[A].dropna().iloc[0])
top = float(np.interp(a, d[X], d[D])) if not DISCRETE else float(d[D].max()) * 0.08
fig.add_trace(go.Scatter(x=[a, a], y=[0, top], mode="lines", line=dict(color=colour, dash="dash", width=1.5), showlegend=False, hovertext=f"actual {a:g}"))
if not DISCRETE:
fig.add_trace(go.Scatter(x=[a], y=[top], mode="markers", marker=dict(symbol=SERIES_MARKERS[i % 8], color="white", size=8, line=dict(color=colour, width=1.6)), showlegend=False))
fig.update_layout(xaxis_title=X, yaxis_title=D, barmode="group")
fig.show()Needs pandas, numpy, plotly · reads predicted-distributions-demo.csv · app theme from the optional codesplash helper
# Predicted distributions — Codesplash Chart Lab (recipe "predicted-distributions")
# controls: discrete=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))
# non-colour encodings per series (same table as the app: series are never told apart by colour alone)
cs_linetypes <- c("solid", "63", "23", "8323", "C4", "33", "822222", "25")
cs_shapes <- c(16, 15, 17, 18, 3, 8, 4, 25)
df <- read.csv("predicted-distributions-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["row"]] <- factor(df[["row"]], levels = c("row 12 (actual 25.1)", "row 47 (actual 19.3)", "row 3 (actual 50.6)", "row 88 (actual 88.2)", "row 61 (actual 72.8)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
X <- "ozone (ppb)"
D <- "density"
S <- "row"
A <- "actual"
discrete <- FALSE
d <- data.frame(x = df[[X]], dens = df[[D]], s = factor(df[[S]], levels = levels_of(df[[S]])))
if (!is.null(A)) d$a <- df[[A]]
d <- d[order(d$s, d$x), ]
p <- ggplot(d, aes(x, dens, colour = s))
if (discrete) {
p <- p + geom_linerange(aes(ymin = 0, ymax = dens), position = position_dodge(width = 0.5)) +
geom_point(aes(shape = s), position = position_dodge(width = 0.5), size = 1.4) # marker shape per row, as in the app
} else {
p <- p + geom_area(aes(fill = s), position = "identity", alpha = 0.08, colour = NA, show.legend = FALSE) + geom_line(aes(linetype = s), linewidth = 0.6) # dash per row
}
if (!is.null(A)) {
act <- do.call(rbind, lapply(split(d, d$s, drop = TRUE), function(g) {
a <- g$a[!is.na(g$a)][1]
data.frame(s = g$s[1], a = a, top = if (discrete) max(g$dens) * 0.08 else stats::approx(g$x, g$dens, a, rule = 2)$y)
}))
p <- p + geom_segment(data = act, aes(x = a, xend = a, y = 0, yend = top, colour = s), linetype = "dashed", linewidth = 0.45)
if (!discrete) p <- p + geom_point(data = act, aes(x = a, y = top, colour = s, shape = s), size = 2, show.legend = FALSE) # the row's marker at the actual
}
p <- p + scale_colour_manual(values = rep(cs_cat, length.out = nlevels(d$s))) +
scale_fill_manual(values = rep(cs_cat, length.out = nlevels(d$s))) + scale_linetype_manual(values = cs_linetypes) +
scale_shape_manual(values = cs_shapes) + labs(x = X, y = D, colour = NULL, linetype = NULL, shape = NULL)
print(p)Needs ggplot2 · reads predicted-distributions-demo.csv · app theme from the optional codesplashr helper