svginterval-plot
Prediction intervals
Which observations fall outside their prediction intervals, and how wide are the intervals?
How to read it
- Read each bar as a row's prediction interval.
- Dots are the actual values.
- Red dots fall outside: are they at some part of the range or evenly scattered?
- Callout 1: One row's interval.
- Callout 2: A value outside its interval.
- Callout 3: The share covered.
Watch out
- Width matters too: wide intervals are easy to keep correct but tell you little.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Observations are ordered by `index` as sent (often sorted by the prediction or by time). Coverage counts actuals within [lower, upper].
# Prediction intervals — Codesplash Chart Lab (recipe "interval-plot")
# controls: defaults
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("interval-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
I = "sale (sorted by prediction)"
A = "price ($100k)"
P = "predicted"
LO = "lower"
HI = "upper"
d = df.dropna(subset=[I, LO, HI]).sort_values(I)
inside = (d[A] >= d[LO]) & (d[A] <= d[HI])
fig, ax = plt.subplots(figsize=(8, 4.5))
if len(d) > 400:
ax.fill_between(d[I], d[LO], d[HI], color=PALETTE[0], alpha=0.25, lw=0)
else:
ax.vlines(d[I], d[LO], d[HI], color=PALETTE[0], alpha=0.45, linewidth=3)
ax.plot(d[I], d[P], color=PALETTE[0], linewidth=1.2, label="prediction")
ax.scatter(d.loc[inside, I], d.loc[inside, A], color="black", s=8, label=f"actual inside ({inside.mean():.1%} covered)")
ax.scatter(d.loc[~inside, I], d.loc[~inside, A], color="#ce5342", s=14, label="actual outside")
ax.set_xlabel(I)
ax.set_ylabel(A)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads interval-plot-demo.csv · app theme from the optional codesplash helper
# Prediction intervals — Codesplash Chart Lab (recipe "interval-plot")
# controls: defaults
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("interval-plot-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
I = "sale (sorted by prediction)"
A = "price ($100k)"
P = "predicted"
LO = "lower"
HI = "upper"
d = df.dropna(subset=[I, LO, HI]).sort_values(I)
inside = (d[A] >= d[LO]) & (d[A] <= d[HI])
fig = go.Figure()
fig.add_scatter(x=d[I], y=d[LO], mode="lines", line_width=0, showlegend=False, hoverinfo="skip")
fig.add_scatter(x=d[I], y=d[HI], mode="lines", line_width=0, fill="tonexty", fillcolor="rgba(41, 113, 198, 0.25)", name="interval")
fig.add_scatter(x=d[I], y=d[P], mode="lines", line=dict(color=PALETTE[0], width=1.5), name="prediction")
fig.add_scatter(x=d[I], y=d[A], mode="markers", marker=dict(color=np.where(inside, "black", "#ce5342"), size=5), name="actual")
fig.update_layout(xaxis_title=I, yaxis_title=A)
fig.show()Needs pandas, numpy, plotly · reads interval-plot-demo.csv · app theme from the optional codesplash helper
# Prediction intervals — Codesplash Chart Lab (recipe "interval-plot")
# controls: defaults
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("interval-plot-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
i_col <- "sale (sorted by prediction)"
a_col <- "price ($100k)"
p_col <- "predicted"
lo_col <- "lower"
hi_col <- "upper"
d <- data.frame(i = df[[i_col]], a = df[[a_col]], pr = df[[p_col]], lo = df[[lo_col]], hi = df[[hi_col]])
d <- d[order(d$i), ]
d$inside <- d$a >= d$lo & d$a <= d$hi
p <- ggplot(d, aes(i)) +
{ if (nrow(d) > 400) geom_ribbon(aes(ymin = lo, ymax = hi), fill = cs_cat[1], alpha = 0.25) else geom_linerange(aes(ymin = lo, ymax = hi), colour = cs_cat[1], alpha = 0.45, linewidth = 1.2) } +
geom_line(aes(y = pr), colour = cs_cat[1]) + geom_point(aes(y = a, colour = inside), size = 1.2) +
scale_colour_manual(values = c("FALSE" = "#ce5342", "TRUE" = "black"), labels = c("outside", "inside"), name = "actual") +
labs(x = i_col, y = a_col) + theme_cs
print(p)Needs ggplot2 · reads interval-plot-demo.csv · app theme from the optional codesplashr helper