Skip to content
svgrisk-group-km

Survival by risk group

Do people the model calls riskier actually have the event sooner?

Demo data · seed 20261101 · 48 rows · default settings · 640 × 360SVG, lightSVG, darkDemo CSV

How to read it

  1. Read each line as the share of one predicted-risk group still event-free over time.
  2. Check the order: the low-risk line should stay on top and the high-risk line at the bottom.
  3. Read the gap between lines: wider means the score separates people more, and crossing lines mean it stops doing so.
  1. Callout 1: The group the model scored as lowest risk.
  2. Callout 2: The group it scored as highest risk.
  3. 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