svgloglog-survival
Log–log survival plot
Are the hazards proportional, and could the times be Weibull?
How to read it
- Read x as log time and y as log(−log S(t)), the scale on which proportional hazards plot as parallel curves.
- Parallel curves support proportional hazards; curves that converge or cross do not.
- A straight line for a group supports a Weibull lifetime for that group.
- Callout 1: A wide gap early on.
- Callout 2: The curves meet here, so the hazard ratio is changing.
- Callout 3: One curve per group.
Watch out
- The far left rests on a handful of events, so give those steps little weight.
- When the curves are not parallel, the single hazard ratio from a log-rank or Cox model is an average over time.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Points with S(t) = 0 or 1 are left out, because the transform is infinite there.
# Log–log survival plot — Codesplash Chart Lab (recipe "loglog-survival")
# 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("loglog-survival-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["control", "treated"])
_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")
T = "days"
Y = "survival"
G = "arm"
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)))
def curves():
groups = levels_of(df[G]) if G else [None]
for g in groups:
d = df if g is None else df[df[G].astype(str) == str(g)]
d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
t, v = d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
keep = (t > 0) & (v > 0) & (v < 1)
t, v = t[keep], v[keep]
yield ("all" if g is None else str(g)), np.log(t), np.log(-np.log(v))
fig, ax = plt.subplots(figsize=(8, 4.5))
for i, (name, t, y) in enumerate(curves()):
ax.step(t, y, where="post", color=PALETTE[i % len(PALETTE)], label=name)
ax.set_xlabel(f"log {T}")
ax.set_ylabel("log(−log S(t))")
ax.set_title("Log–log survival: parallel curves mean proportional hazards", fontsize=10, loc="left")
ax.legend(frameon=False)
plt.show()Needs pandas, numpy, matplotlib · reads loglog-survival-demo.csv · app theme from the optional codesplash helper
# Log–log survival plot — Codesplash Chart Lab (recipe "loglog-survival")
# 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("loglog-survival-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["arm"] = pd.Categorical(df["arm"].astype("string"), categories=["control", "treated"])
_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")
T = "days"
Y = "survival"
G = "arm"
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)))
def curves():
groups = levels_of(df[G]) if G else [None]
for g in groups:
d = df if g is None else df[df[G].astype(str) == str(g)]
d = d.dropna(subset=[T, Y]).sort_values(T, kind="stable")
t, v = d[T].to_numpy(dtype=float), d[Y].to_numpy(dtype=float)
keep = (t > 0) & (v > 0) & (v < 1)
t, v = t[keep], v[keep]
yield ("all" if g is None else str(g)), np.log(t), np.log(-np.log(v))
fig = go.Figure()
for i, (name, t, y) in enumerate(curves()):
fig.add_scatter(x=t, y=y, mode="lines", name=name, line=dict(color=PALETTE[i % len(PALETTE)], shape="hv"))
fig.update_layout(title="Log–log survival: parallel curves mean proportional hazards", xaxis_title=f"log {T}", yaxis_title="log(−log S(t))")
fig.show()Needs pandas, numpy, plotly · reads loglog-survival-demo.csv · app theme from the optional codesplash helper
# Log–log survival plot — Codesplash Chart Lab (recipe "loglog-survival")
# 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("loglog-survival-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["arm"]] <- factor(df[["arm"]], levels = c("control", "treated"))
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
t_col <- "days"
y_col <- "survival"
g_col <- "arm"
levels_of <- function(v) if (is.factor(v)) levels(droplevels(v)) else unique(as.character(v[!is.na(v)]))
grp <- if (is.null(g_col)) rep("all", nrow(df)) else as.character(df[[g_col]])
lv <- if (is.null(g_col)) "all" else levels_of(df[[g_col]])
pd <- do.call(rbind, lapply(lv, function(g) {
d <- df[grp == g & !is.na(df[[t_col]]) & !is.na(df[[y_col]]), , drop = FALSE]
d <- d[order(d[[t_col]]), , drop = FALSE]
t <- d[[t_col]]
v <- d[[y_col]]
keep <- t > 0 & v > 0 & v < 1
data.frame(x = log(t[keep]), y = (function(v) log(-log(v)))(v[keep]), g = factor(g, levels = lv))
}))
p <- ggplot(pd, aes(x, y, colour = g)) + geom_step() + scale_colour_manual(values = cs_cat, name = NULL) +
labs(x = paste("log", t_col), y = "log(−log S(t))", title = "Log–log survival: parallel curves mean proportional hazards") + theme_cs
print(p)Needs ggplot2 · reads loglog-survival-demo.csv · app theme from the optional codesplashr helper