svgrisk-group-km
Survival by risk group
Do people the model calls riskier actually have the event sooner?
How to read it
- Read each line as the share of one predicted-risk group still event-free over time.
- Check the order: the low-risk line should stay on top and the high-risk line at the bottom.
- Read the gap between lines: wider means the score separates people more, and crossing lines mean it stops doing so.
- Callout 1: The group the model scored as lowest risk.
- Callout 2: The group it scored as highest risk.
- Callout 3: Each group's label gives its size.
Watch out
- Equal-sized groups are a display choice. Separation between thirds doesn't mean there are three natural kinds of patient.
- These are observed curves on held-out rows, so they show how well the model ranks, not that its probabilities are calibrated.
Defaults
No settings: the chart draws one way.
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.
- Rows are sorted by predicted risk and cut into equal-sized groups; each curve is a plain Kaplan–Meier estimate of that group's observed times. Survival starts at 100% at time 0.
# Survival by risk group — Codesplash Chart Lab (recipe "risk-group-km")
# 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"]
# 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))]
df = pd.read_csv("risk-group-km-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Risk group"] = pd.Categorical(df["Risk group"].astype("string"), categories=["Low risk (n = 76)", "Middle risk (n = 76)", "High risk (n = 76)"])
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)))
T = "Days"
S = "Survival"
G = "Risk group"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
end = float(df[T].max())
fig, ax = plt.subplots(figsize=(7, 4.5))
for i, (name, d) in enumerate(series):
d = d.dropna(subset=[T, S]).sort_values(T)
# Every curve starts at survival 1 at time 0 and holds its last value to the end.
x = np.concatenate([[0.0], d[T], [end]])
y = np.concatenate([[1.0], d[S], [d[S].iloc[-1] if len(d) else 1.0]])
ax.step(x, y, where="post", color=PALETTE[i % len(PALETTE)], linewidth=1.8, linestyle=SERIES_DASHES[i % 8], label=name or S) # dash per group, as in the app
ax.set_xlim(0, end)
ax.set_ylim(0, 1)
ax.yaxis.set_major_formatter(lambda v, _: f"{v:.0%}")
ax.set_xlabel(T)
ax.set_ylabel(S)
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads risk-group-km-demo.csv · app theme from the optional codesplash helper
# Survival by risk group — Codesplash Chart Lab (recipe "risk-group-km")
# 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
# 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"]
df = pd.read_csv("risk-group-km-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["Risk group"] = pd.Categorical(df["Risk group"].astype("string"), categories=["Low risk (n = 76)", "Middle risk (n = 76)", "High risk (n = 76)"])
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)))
T = "Days"
S = "Survival"
G = "Risk group"
groups = levels_of(df[G]) if G else [None]
series = []
for name in groups:
d = df if name is None else df[df[G].astype(str) == str(name)]
series.append((name if name is not None else "", d.dropna(subset=[T]).sort_values([T], kind="mergesort")))
end = float(df[T].max())
fig = go.Figure()
for i, (name, d) in enumerate(series):
d = d.dropna(subset=[T, S]).sort_values(T)
x = [0.0] + d[T].tolist() + [end]
y = [1.0] + d[S].tolist() + [d[S].iloc[-1] if len(d) else 1.0]
fig.add_trace(go.Scatter(x=x, y=y, mode="lines", line_shape="hv", line_color=PALETTE[i % len(PALETTE)], line_dash=SERIES_DASHES[i % 8], name=name or S)) # dash per group
fig.update_layout(xaxis_title=T, yaxis_title=S, yaxis_range=[0, 1], yaxis_tickformat=".0%")
fig.show()Needs pandas, numpy, plotly · reads risk-group-km-demo.csv · app theme from the optional codesplash helper
# Survival by risk group — Codesplash Chart Lab (recipe "risk-group-km")
# 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))
# 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")
df <- read.csv("risk-group-km-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["Risk group"]] <- factor(df[["Risk group"]], levels = c("Low risk (n = 76)", "Middle risk (n = 76)", "High risk (n = 76)"))
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
T <- "Days"
S <- "Survival"
G <- "Risk group"
g <- if (is.null(G)) factor(rep("", nrow(df))) else factor(as.character(df[[G]]), levels = levels_of(df[[G]]))
end <- max(df[[T]], na.rm = TRUE)
curves <- do.call(rbind, lapply(levels(g), function(name) {
d <- data.frame(time = df[[T]][g == name], survival = df[[S]][g == name])
d <- d[is.finite(d$time) & is.finite(d$survival), ]
d <- d[order(d$time), ]
last <- if (nrow(d)) d$survival[nrow(d)] else 1
data.frame(group = name, time = c(0, d$time, end), survival = c(1, d$survival, last))
}))
curves$group <- factor(curves$group, levels = levels(g))
p <- ggplot(curves, aes(time, survival, colour = group, linetype = group)) +
geom_step(linewidth = 0.8) + # dash per group, as in the app
scale_colour_manual(values = unname(cs_cat), name = NULL) + scale_linetype_manual(values = cs_linetypes, name = NULL) +
scale_y_continuous(labels = function(v) paste0(round(100 * v), "%"), limits = c(0, 1)) +
labs(x = T, y = S) + theme_cs
print(p)Needs ggplot2 · reads risk-group-km-demo.csv · app theme from the optional codesplashr helper