svgpred-actual
Predicted vs actual
How close are a regression model's predictions to the true values, and where does it miss?
How to read it
- Read each point as one row's prediction and true value.
- Points on the diagonal: right on target.
- Look for bends and funnels: bias at high values or errors that grow.
- Callout 1: Diagonal: perfect prediction.
- Callout 2: Low values above the line: under-predicted.
- Callout 3: Colour: validation or test rows.
Watch out
- Only held-out rows tell you how the model will do on new data.
Defaults
- Identity line (equal axes)
- On
- Draw y = x with equal axes, so distance from the line is the error.
Pinned in the code
- Draws the run's numbers as given (computed by the host's cs-ml evaluation or the Python/R engine); the chart computes nothing statistical.
- Prediction on x and actual on y (scikit-learn's PredictionErrorDisplay); points above the line are under-predicted.
- With the identity line on, both axes share one range so the 45° line means equality.
- Validation points are out-of-fold predictions; test points come from the final model, scored once.
# Predicted vs actual — Codesplash Chart Lab (recipe "pred-actual")
# controls: identity=true
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("pred-actual-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["split"] = pd.Categorical(df["split"].astype("string"), categories=["validation", "test"])
_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")
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)))
ACT = "sale price (k€)"
PRED = "predicted price (k€)"
SET = "split"
IDENTITY = True
d = df.dropna(subset=[ACT, PRED])
sets = levels_of(d[SET]) if SET else [None]
fig, ax = plt.subplots(figsize=(6, 6))
for i, s in enumerate(sets):
g = d if s is None else d[d[SET].astype(str) == str(s)]
ax.scatter(g[PRED], g[ACT], s=12, alpha=0.6, color=PALETTE[i % len(PALETTE)], label=str(s) if s is not None else None)
lo, hi = float(min(d[ACT].min(), d[PRED].min())), float(max(d[ACT].max(), d[PRED].max()))
if IDENTITY:
ax.plot([lo, hi], [lo, hi], color=REF, linestyle="--", linewidth=1, label="perfect prediction (y = x)")
ax.set_xlabel(PRED)
ax.set_ylabel(ACT)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads pred-actual-demo.csv · app theme from the optional codesplash helper
# Predicted vs actual — Codesplash Chart Lab (recipe "pred-actual")
# controls: identity=true
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("pred-actual-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["split"] = pd.Categorical(df["split"].astype("string"), categories=["validation", "test"])
_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")
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)))
ACT = "sale price (k€)"
PRED = "predicted price (k€)"
SET = "split"
IDENTITY = True
d = df.dropna(subset=[ACT, PRED])
sets = levels_of(d[SET]) if SET else [None]
fig = go.Figure()
for i, s in enumerate(sets):
g = d if s is None else d[d[SET].astype(str) == str(s)]
fig.add_scatter(x=g[PRED], y=g[ACT], mode="markers", name=str(s) if s is not None else ACT, marker=dict(color=PALETTE[i % len(PALETTE)], size=5, opacity=0.6))
lo, hi = float(min(d[ACT].min(), d[PRED].min())), float(max(d[ACT].max(), d[PRED].max()))
if IDENTITY:
fig.add_scatter(x=[lo, hi], y=[lo, hi], mode="lines", line=dict(color=REF, dash="dash", width=1), name="y = x")
fig.update_layout(xaxis_title=PRED, yaxis_title=ACT)
fig.show()Needs pandas, numpy, plotly · reads pred-actual-demo.csv · app theme from the optional codesplash helper
# Predicted vs actual — Codesplash Chart Lab (recipe "pred-actual")
# controls: identity=true
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("pred-actual-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["split"]] <- factor(df[["split"]], levels = c("validation", "test"))
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
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
act_col <- "sale price (k€)"
pred_col <- "predicted price (k€)"
set_col <- "split"
show_identity <- TRUE
d <- df[!is.na(df[[act_col]]) & !is.na(df[[pred_col]]), ]
d <- data.frame(a = d[[act_col]], p = d[[pred_col]], s = if (is.null(set_col)) "" else factor(as.character(d[[set_col]]), levels = levels_of(d[[set_col]])))
p <- ggplot(d, aes(p, a, colour = s)) +
{ if (show_identity) geom_abline(slope = 1, intercept = 0, linetype = "dashed", colour = ref_col) } +
geom_point(alpha = 0.6, size = 1.3) + scale_colour_manual(values = cs_cat, guide = if (is.null(set_col)) "none" else "legend") +
labs(x = pred_col, y = act_col, colour = NULL) + theme_cs
print(p)Needs ggplot2 · reads pred-actual-demo.csv · app theme from the optional codesplashr helper