Hazards, medians and the area under the curve
Connect the moment-to-moment hazard to the survival curve, then choose between the median, survival at a time point, and restricted mean survival.
What runs in CodeSplash
- Kaplan–Meier survival curves Verified in Python and R
You will be able to
- Explain how a hazard builds up into a survival curve
- Read median survival, survival at a chosen time, and restricted mean survival from a curve
- Say when the median can't be estimated and what to report instead
Read first
Risk now, survival so far
ReadTwo curves describe the same waiting time.
The survival functionSurvival functionThe probability of remaining free of the event beyond time t. It starts at 1 and can only fall. is the chance of getting past time . It can only fall.
The hazardHazardThe moment-to-moment risk of the event among those still at risk. is the event rate right now among those still event-free. It can rise, fall or wobble.
Every moment's risk adds up, and survival is what is left.
Move the hazard
ExploreThe shape controls how risk changes over time: below 1 risk falls, above 1 it rises. Predict what happens to each survival curve before you drag.
FExplorable · From hazard to survival
How does the moment-to-moment risk build up into a survival curve?
What share of group A is still event-free at this time?
Below 1 risk falls with time; above 1 it rises.
Hazard: risk at each moment
Survival: still event-free
Commit your prediction above to see the result
Make your prediction to see the result.
Now make the hazards cross by changing one group's shape. Watch what a single "hazard ratio" would have to average over.
Three ways to summarize
PredictPredict first
A trial ends after two years with 70% of patients still event-free. What can you say about the median survival time?
Reveal
It can't be estimated: the curve never reached 50%. This is common in good-prognosis groups, and it's a reason to report survival at fixed times or a restricted mean as well. A software result of "NA" here isn't a failure.
The restricted mean
ReadRestricted mean survival timeRestricted mean survival timeThe average event-free time up to a horizon τ, the area under the survival curve; a difference in RMST is a difference in time. is the area under the curve up to a horizon : the average time lived during that window.
In the lung data, over the first 365 days, patients lived 263 days on average (standard error 7.8).
Unlike the median, it exists whenever you have follow-up to , and "a difference of 30 days lived over the first year" is a sentence anyone can act on. Choose before looking at the curves, and keep it inside the follow-up you really have.
View data
| months | survival | lower | upper | arm | n.risk | n.censor |
|---|---|---|---|---|---|---|
| 0 | 1 | 1 | 1 | standard | 60 | 0 |
| 0.1000 | 0.9833 | 0.8875 | 0.9976 | standard | 60 | 0 |
| 0.2000 | 0.9667 | 0.8732 | 0.9916 | standard | 59 | 0 |
| 0.5000 | 0.9500 | 0.8529 | 0.9836 | standard | 58 | 0 |
| 0.6000 | 0.9333 | 0.8321 | 0.9744 | standard | 57 | 0 |
| 0.9000 | 0.9167 | 0.8113 | 0.9644 | standard | 56 | 0 |
| 1.400 | 0.9000 | 0.7909 | 0.9538 | standard | 55 | 0 |
| 1.900 | 0.8833 | 0.7708 | 0.9426 | standard | 54 | 0 |
| 2.200 | 0.8667 | 0.7510 | 0.9310 | standard | 53 | 0 |
| 2.400 | 0.8500 | 0.7316 | 0.9190 | standard | 52 | 0 |
| 2.600 | 0.8333 | 0.7124 | 0.9066 | standard | 51 | 0 |
| 2.900 | 0.8167 | 0.6935 | 0.8940 | standard | 50 | 0 |
| 3.600 | 0.7833 | 0.6563 | 0.8680 | standard | 49 | 0 |
| 4 | 0.7667 | 0.6381 | 0.8546 | standard | 47 | 0 |
| 4.900 | 0.7500 | 0.6200 | 0.8410 | standard | 46 | 0 |
| 5 | 0.7167 | 0.5845 | 0.8133 | standard | 45 | 0 |
| 5.500 | 0.7000 | 0.5669 | 0.7992 | standard | 43 | 0 |
| 6 | 0.6833 | 0.5496 | 0.7849 | standard | 42 | 0 |
| 6.200 | 0.6833 | 0.5496 | 0.7849 | standard | 41 | 1 |
| 6.300 | 0.6662 | 0.5318 | 0.7702 | standard | 40 | 0 |
| 6.600 | 0.6492 | 0.5142 | 0.7553 | standard | 39 | 0 |
| 6.800 | 0.6321 | 0.4968 | 0.7402 | standard | 38 | 0 |
| 7.700 | 0.6150 | 0.4796 | 0.7250 | standard | 37 | 0 |
| 7.700 | 0.6150 | 0.4796 | 0.7250 | standard | 36 | 1 |
| 7.900 | 0.6150 | 0.4796 | 0.7250 | standard | 35 | 1 |
| 8.100 | 0.6150 | 0.4796 | 0.7250 | standard | 34 | 1 |
| 9.100 | 0.5964 | 0.4605 | 0.7086 | standard | 33 | 0 |
| 9.500 | 0.5777 | 0.4416 | 0.6919 | standard | 32 | 0 |
| 9.800 | 0.5777 | 0.4416 | 0.6919 | standard | 31 | 1 |
| 10.200 | 0.5585 | 0.4221 | 0.6747 | standard | 30 | 0 |
| 11.100 | 0.5585 | 0.4221 | 0.6747 | standard | 29 | 1 |
| 11.400 | 0.5585 | 0.4221 | 0.6747 | standard | 28 | 1 |
| 11.900 | 0.5378 | 0.4010 | 0.6563 | standard | 27 | 0 |
| 12.100 | 0.5171 | 0.3803 | 0.6377 | standard | 26 | 0 |
| 12.300 | 0.4964 | 0.3599 | 0.6188 | standard | 25 | 0 |
| 13.200 | 0.4757 | 0.3398 | 0.5997 | standard | 24 | 0 |
| 13.500 | 0.4550 | 0.3201 | 0.5803 | standard | 23 | 0 |
| 13.700 | 0.4344 | 0.3006 | 0.5607 | standard | 22 | 0 |
| 14.200 | 0.4137 | 0.2815 | 0.5408 | standard | 21 | 0 |
| 14.700 | 0.3930 | 0.2627 | 0.5207 | standard | 20 | 0 |
| 15.300 | 0.3930 | 0.2627 | 0.5207 | standard | 19 | 1 |
| 15.800 | 0.3712 | 0.2428 | 0.4996 | standard | 18 | 0 |
| 16.100 | 0.3493 | 0.2234 | 0.4781 | standard | 17 | 0 |
| 17.700 | 0.3493 | 0.2234 | 0.4781 | standard | 16 | 1 |
| 17.700 | 0.3260 | 0.2026 | 0.4553 | standard | 15 | 0 |
| 18.500 | 0.3260 | 0.2026 | 0.4553 | standard | 14 | 1 |
| 19.500 | 0.3010 | 0.1804 | 0.4309 | standard | 13 | 0 |
| 19.700 | 0.2759 | 0.1589 | 0.4059 | standard | 12 | 0 |
| 21.900 | 0.2508 | 0.1382 | 0.3804 | standard | 11 | 0 |
| 22.500 | 0.2257 | 0.1182 | 0.3543 | standard | 10 | 0 |
| 23.300 | 0.2006 | 0.0991 | 0.3275 | standard | 9 | 0 |
| 24.200 | 0.2006 | 0.0991 | 0.3275 | standard | 8 | 1 |
| 26.500 | 0.1720 | 0.0774 | 0.2978 | standard | 7 | 0 |
| 28.100 | 0.1433 | 0.0574 | 0.2669 | standard | 6 | 0 |
| 28.400 | 0.1147 | 0.0394 | 0.2344 | standard | 5 | 0 |
| 28.700 | 0.0860 | 0.0237 | 0.2002 | standard | 4 | 0 |
| 33 | 0.0573 | 0.0109 | 0.1639 | standard | 3 | 0 |
| 44.300 | 0.0573 | 0.0109 | 0.1639 | standard | 2 | 1 |
| 44.500 | 0 | — | — | standard | 1 | 0 |
| 0 | 1 | 1 | 1 | new therapy | 60 | 0 |
First 60 of 114 rows.
Read a card
In the appHere is the card for men and women in the lung data, with a 500-day horizon. Find each group's median, its survival at the listed times, and its restricted mean.
median survival = 310; log-rank χ²(1) = 10.33, p = .001
- Events
- 165
- Median survival
- 310
- 95% CI
- [285, 363]
- Log-rank p
- .001
Plots
View data
| upper | lower | Censored | At risk | sex | Survival probability | time |
|---|---|---|---|---|---|---|
| 1 | 1 | 0 | 138 | male | 1 | 0 |
| 1 | 0.9542 | 0 | 138 | male | 0.9783 | 11 |
| 0.9994 | 0.9434 | 0 | 135 | male | 0.9710 | 12 |
| 0.9912 | 0.9231 | 0 | 134 | male | 0.9565 | 13 |
| 0.9866 | 0.9134 | 0 | 132 | male | 0.9493 | 15 |
| 0.9818 | 0.9038 | 0 | 131 | male | 0.9420 | 26 |
| 0.9769 | 0.8945 | 0 | 130 | male | 0.9348 | 30 |
| 0.9718 | 0.8853 | 0 | 129 | male | 0.9275 | 31 |
| 0.9613 | 0.8672 | 0 | 128 | male | 0.9130 | 53 |
| 0.9559 | 0.8583 | 0 | 126 | male | 0.9058 | 54 |
| 0.9504 | 0.8496 | 0 | 125 | male | 0.8986 | 59 |
| 0.9448 | 0.8409 | 0 | 124 | male | 0.8913 | 60 |
| 0.9334 | 0.8237 | 0 | 123 | male | 0.8768 | 65 |
| 0.9276 | 0.8152 | 0 | 121 | male | 0.8696 | 71 |
| 0.9218 | 0.8067 | 0 | 120 | male | 0.8623 | 81 |
| 0.9099 | 0.7900 | 0 | 119 | male | 0.8478 | 88 |
| 0.9039 | 0.7817 | 0 | 117 | male | 0.8406 | 92 |
| 0.8979 | 0.7734 | 0 | 116 | male | 0.8333 | 93 |
| 0.8918 | 0.7652 | 0 | 115 | male | 0.8261 | 95 |
| 0.8857 | 0.7570 | 0 | 114 | male | 0.8188 | 105 |
| 0.8795 | 0.7489 | 0 | 113 | male | 0.8116 | 107 |
| 0.8733 | 0.7408 | 0 | 112 | male | 0.8043 | 110 |
| 0.8671 | 0.7328 | 0 | 111 | male | 0.7971 | 116 |
| 0.8608 | 0.7247 | 0 | 110 | male | 0.7899 | 118 |
| 0.8545 | 0.7167 | 0 | 109 | male | 0.7826 | 131 |
| 0.8419 | 0.7008 | 0 | 108 | male | 0.7681 | 132 |
| 0.8355 | 0.6929 | 0 | 106 | male | 0.7609 | 135 |
| 0.8291 | 0.6851 | 0 | 105 | male | 0.7536 | 142 |
| 0.8226 | 0.6772 | 0 | 104 | male | 0.7464 | 144 |
| 0.8161 | 0.6694 | 0 | 103 | male | 0.7391 | 147 |
| 0.8031 | 0.6538 | 0 | 102 | male | 0.7246 | 156 |
| 0.7834 | 0.6306 | 0 | 100 | male | 0.7029 | 163 |
| 0.7768 | 0.6230 | 0 | 97 | male | 0.6957 | 166 |
| 0.7702 | 0.6153 | 0 | 96 | male | 0.6884 | 170 |
| 0.7702 | 0.6153 | 1 | 95 | male | 0.6884 | 174 |
| 0.7635 | 0.6076 | 0 | 94 | male | 0.6811 | 175 |
| 0.7567 | 0.5999 | 0 | 93 | male | 0.6738 | 176 |
| 0.7500 | 0.5922 | 0 | 92 | male | 0.6664 | 177 |
| 0.7364 | 0.5769 | 0 | 91 | male | 0.6518 | 179 |
| 0.7296 | 0.5693 | 0 | 89 | male | 0.6445 | 180 |
| 0.7159 | 0.5541 | 0 | 88 | male | 0.6298 | 181 |
| 0.7090 | 0.5466 | 0 | 86 | male | 0.6225 | 183 |
| 0.7090 | 0.5466 | 1 | 85 | male | 0.6225 | 185 |
| 0.7090 | 0.5466 | 1 | 84 | male | 0.6225 | 188 |
| 0.7020 | 0.5388 | 0 | 83 | male | 0.6150 | 189 |
| 0.7020 | 0.5388 | 1 | 82 | male | 0.6150 | 191 |
| 0.7020 | 0.5388 | 1 | 81 | male | 0.6150 | 196 |
| 0.6948 | 0.5309 | 1 | 80 | male | 0.6073 | 197 |
| 0.6875 | 0.5228 | 0 | 78 | male | 0.5995 | 202 |
| 0.6802 | 0.5148 | 0 | 77 | male | 0.5917 | 207 |
| 0.6728 | 0.5068 | 0 | 76 | male | 0.5839 | 210 |
| 0.6655 | 0.4988 | 0 | 75 | male | 0.5762 | 212 |
| 0.6581 | 0.4909 | 0 | 74 | male | 0.5684 | 218 |
| 0.6581 | 0.4909 | 1 | 73 | male | 0.5684 | 221 |
| 0.6506 | 0.4829 | 1 | 72 | male | 0.5605 | 222 |
| 0.6430 | 0.4747 | 0 | 70 | male | 0.5525 | 223 |
| 0.6430 | 0.4747 | 2 | 69 | male | 0.5525 | 225 |
| 0.6352 | 0.4663 | 0 | 67 | male | 0.5442 | 229 |
| 0.6274 | 0.4579 | 0 | 66 | male | 0.5360 | 230 |
| 0.6274 | 0.4579 | 1 | 65 | male | 0.5360 | 237 |
First 60 of 208 rows.
View data
| sex | Survival probability | time |
|---|---|---|
| male | 1 | 0 |
| male | 0.9783 | 11 |
| male | 0.9710 | 12 |
| male | 0.9565 | 13 |
| male | 0.9493 | 15 |
| male | 0.9420 | 26 |
| male | 0.9348 | 30 |
| male | 0.9275 | 31 |
| male | 0.9130 | 53 |
| male | 0.9058 | 54 |
| male | 0.8986 | 59 |
| male | 0.8913 | 60 |
| male | 0.8768 | 65 |
| male | 0.8696 | 71 |
| male | 0.8623 | 81 |
| male | 0.8478 | 88 |
| male | 0.8406 | 92 |
| male | 0.8333 | 93 |
| male | 0.8261 | 95 |
| male | 0.8188 | 105 |
| male | 0.8116 | 107 |
| male | 0.8043 | 110 |
| male | 0.7971 | 116 |
| male | 0.7899 | 118 |
| male | 0.7826 | 131 |
| male | 0.7681 | 132 |
| male | 0.7609 | 135 |
| male | 0.7536 | 142 |
| male | 0.7464 | 144 |
| male | 0.7391 | 147 |
| male | 0.7246 | 156 |
| male | 0.7029 | 163 |
| male | 0.6957 | 166 |
| male | 0.6884 | 170 |
| male | 0.6884 | 174 |
| male | 0.6811 | 175 |
| male | 0.6738 | 176 |
| male | 0.6664 | 177 |
| male | 0.6518 | 179 |
| male | 0.6445 | 180 |
| male | 0.6298 | 181 |
| male | 0.6225 | 183 |
| male | 0.6225 | 185 |
| male | 0.6225 | 188 |
| male | 0.6150 | 189 |
| male | 0.6150 | 191 |
| male | 0.6150 | 196 |
| male | 0.6073 | 197 |
| male | 0.5995 | 202 |
| male | 0.5917 | 207 |
| male | 0.5839 | 210 |
| male | 0.5762 | 212 |
| male | 0.5684 | 218 |
| male | 0.5684 | 221 |
| male | 0.5605 | 222 |
| male | 0.5525 | 223 |
| male | 0.5525 | 225 |
| male | 0.5442 | 229 |
| male | 0.5360 | 230 |
| male | 0.5360 | 237 |
First 60 of 208 rows.
View data
| sex | Survival probability | time |
|---|---|---|
| male | 1 | 0 |
| male | 0.9783 | 11 |
| male | 0.9710 | 12 |
| male | 0.9565 | 13 |
| male | 0.9493 | 15 |
| male | 0.9420 | 26 |
| male | 0.9348 | 30 |
| male | 0.9275 | 31 |
| male | 0.9130 | 53 |
| male | 0.9058 | 54 |
| male | 0.8986 | 59 |
| male | 0.8913 | 60 |
| male | 0.8768 | 65 |
| male | 0.8696 | 71 |
| male | 0.8623 | 81 |
| male | 0.8478 | 88 |
| male | 0.8406 | 92 |
| male | 0.8333 | 93 |
| male | 0.8261 | 95 |
| male | 0.8188 | 105 |
| male | 0.8116 | 107 |
| male | 0.8043 | 110 |
| male | 0.7971 | 116 |
| male | 0.7899 | 118 |
| male | 0.7826 | 131 |
| male | 0.7681 | 132 |
| male | 0.7609 | 135 |
| male | 0.7536 | 142 |
| male | 0.7464 | 144 |
| male | 0.7391 | 147 |
| male | 0.7246 | 156 |
| male | 0.7029 | 163 |
| male | 0.6957 | 166 |
| male | 0.6884 | 170 |
| male | 0.6884 | 174 |
| male | 0.6811 | 175 |
| male | 0.6738 | 176 |
| male | 0.6664 | 177 |
| male | 0.6518 | 179 |
| male | 0.6445 | 180 |
| male | 0.6298 | 181 |
| male | 0.6225 | 183 |
| male | 0.6225 | 185 |
| male | 0.6225 | 188 |
| male | 0.6150 | 189 |
| male | 0.6150 | 191 |
| male | 0.6150 | 196 |
| male | 0.6073 | 197 |
| male | 0.5995 | 202 |
| male | 0.5917 | 207 |
| male | 0.5839 | 210 |
| male | 0.5762 | 212 |
| male | 0.5684 | 218 |
| male | 0.5684 | 221 |
| male | 0.5605 | 222 |
| male | 0.5525 | 223 |
| male | 0.5525 | 225 |
| male | 0.5442 | 229 |
| male | 0.5360 | 230 |
| male | 0.5360 | 237 |
First 60 of 208 rows.
Assumptions
- Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
- Number of events — At least 10 events per curve.
Survival summary
| sex | n | Events | Median | 95% CI low | 95% CI high | RMST (τ = 500) | SE |
|---|---|---|---|---|---|---|---|
| All | 228 | 165 | 310 | 285 | 363 | 310.33 | 11.246 |
| male | 138 | 112 | 270 | 212 | 310 | 278.76 | 14.355 |
| female | 90 | 53 | 426 | 348 | 550 | 360.91 | 16.801 |
Survival at chosen times
| sex | Time | At risk | Survival | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | 260 | 113 | 0.5967 | 0.5349 | 0.6656 |
| All | 510 | 41 | 0.2933 | 0.2320 | 0.3707 |
| All | 770 | 9 | 0.0881 | 0.0498 | 0.1560 |
| male | 260 | 61 | 0.5192 | 0.4409 | 0.6114 |
| male | 510 | 20 | 0.2232 | 0.1569 | 0.3176 |
| male | 770 | 7 | 0.0781 | 0.0390 | 0.1563 |
| female | 260 | 52 | 0.7186 | 0.6287 | 0.8214 |
| female | 510 | 21 | 0.4110 | 0.3050 | 0.5540 |
| female | 770 | 2 | 0.0832 | 0.0257 | 0.2697 |
log intervals; Greenwood standard errors.
- Event: status = 2. Intervals: log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
The exact R script · R R version 4.5.1 (2025-06-13)
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 97d5cf030ef37e8c
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(survival)
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/lung.parquet", col_select = c("time", "status", "sex")))
n_input <- nrow(df)
df[["sex"]] <- factor(df[["sex"]], levels = c("male", "female")) # stored level order
df <- df[stats::complete.cases(df[c("time", "status", "sex")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("time", "status", "sex")) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol <- "time"
ecol <- "status"
tt <- as.numeric(df[[tcol]])
if (any(tt < 0)) cs_error("CS_E_INVALID_VALUES", column = tcol, requirement = "zero or positive (survival times)", count = sum(tt < 0))
codes <- sort(unique(df[[ecol]]))
if (all(codes %in% c(0, 1))) {
event_code <- 1 # 0 = censored, 1 = event
} else if (all(codes %in% c(1, 2))) {
event_code <- 2 # 1 = censored, 2 = event (survival::Surv convention)
} else {
stop(sprintf("%s must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column", ecol))
}
ev <- df[[ecol]] == event_code
event_label <- sprintf("%s = %s", ecol, format(event_code))
if (!any(ev)) cs_error("CS_E_NO_EVENTS", event = event_label)
# %% Kaplan–Meier
conf <- 0.95
conf_type <- "log" # pinned: survfit's default is "log"
times <- c()
if (length(times) == 0) times <- cs_default_times(tt)
rmst_tau <- 500 # 0 = no restricted mean
g <- "sex"
levels_g <- levels(df[[g]])
gv <- as.character(df[[g]])
strata <- c(list(All = rep(TRUE, length(tt))), stats::setNames(lapply(levels_g, function(lv) gv == lv), levels_g))
fin <- function(x) if (length(x) == 0 || is.null(x) || !is.finite(x)) NA else unname(x)
values <- list(event_label = event_label, n_groups = if (length(levels_g)) length(levels_g) else NA)
summary_rows <- list()
time_rows <- list()
curve <- list(time = numeric(0), surv = numeric(0), low = numeric(0), high = numeric(0), strata = character(0),
nrisk = numeric(0), ncensor = numeric(0))
for (name in names(strata)) {
m <- strata[[name]]
fit <- survfit(Surv(tt[m], ev[m]) ~ 1, conf.type = conf_type, conf.int = conf)
tb <- summary(fit, rmean = if (rmst_tau > 0) rmst_tau else "none")$table
st <- list(n = sum(m), events = sum(ev[m]), median = fin(tb[["median"]]),
median_low = fin(tb[[grep("LCL$", names(tb))]]), median_high = fin(tb[[grep("UCL$", names(tb))]]),
rmst = if (rmst_tau > 0) fin(tb[["rmean"]]) else NA, rmst_se = if (rmst_tau > 0) fin(tb[["se(rmean)"]]) else NA)
for (k in names(st)) values[[if (name == "All") k else sprintf("%s[%s]", k, name)]] <- st[[k]]
summary_rows[[length(summary_rows) + 1]] <- c(list(group = name), st)
s_at <- cs_step_at(fit$time, fit$surv, times)
l_at <- cs_step_at(fit$time, fit$lower, times)
u_at <- cs_step_at(fit$time, fit$upper, times)
r_at <- cs_n_risk_at(tt[m], times)
for (i in seq_along(times)) {
key <- sprintf("%s@%s", name, cs_key_num(times[i]))
values[[sprintf("surv[%s]", key)]] <- fin(s_at[i])
values[[sprintf("surv_low[%s]", key)]] <- fin(l_at[i])
values[[sprintf("surv_high[%s]", key)]] <- fin(u_at[i])
values[[sprintf("n_risk[%s]", key)]] <- r_at[i]
time_rows[[length(time_rows) + 1]] <- list(group = name, time = times[i], n_risk = r_at[i], surv = fin(s_at[i]),
lower = fin(l_at[i]), upper = fin(u_at[i]))
}
if ((name == "All") == (length(levels_g) == 0)) {
curve$time <- c(curve$time, 0, fit$time)
curve$surv <- c(curve$surv, 1, fit$surv)
curve$low <- c(curve$low, 1, fit$lower)
curve$high <- c(curve$high, 1, fit$upper)
curve$strata <- c(curve$strata, rep(name, length(fit$time) + 1))
curve$nrisk <- c(curve$nrisk, sum(m), fit$n.risk)
curve$ncensor <- c(curve$ncensor, 0, fit$n.censor)
}
}
# %% Log-rank test
if (length(levels_g)) {
lr <- survdiff(Surv(tt, ev) ~ gv, rho = 0)
lr_df <- sum(lr$n > 0) - 1
values$logrank_chisq <- lr$chisq
values$logrank_df <- lr_df
values$logrank_p <- stats::pchisq(lr$chisq, lr_df, lower.tail = FALSE)
} else {
values$logrank_chisq <- NA
values$logrank_df <- NA
values$logrank_p <- NA
}
# %% Assumptions
assumptions <- list(list(key = "censoring", label = "Non-informative censoring", status = "info",
detail = sprintf("%d of %d observations are censored; censoring must be unrelated to prognosis.",
sum(!ev), length(ev))))
few <- character(0)
for (r in summary_rows) if (r$events < 10 && (r$group != "All" || length(levels_g) == 0)) few <- c(few, r$group)
assumptions[[2]] <- if (length(few)) {
list(key = "sample_size", label = "Number of events", status = "warn",
detail = sprintf("Fewer than 10 events in %s; medians and curves are imprecise.", paste(few, collapse = ", ")))
} else {
list(key = "sample_size", label = "Number of events", status = "pass", detail = "At least 10 events per curve.")
}
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
med_text <- if (is.na(values$median)) "not reached" else format(signif(values$median, 4))
summary_cols <- list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "n", label = "n", type = "integer"),
list(key = "events", label = "Events", type = "integer"), list(key = "median", label = "Median", type = "number"),
list(key = "median_low", label = paste(pct, "CI low"), type = "number"), list(key = "median_high", label = paste(pct, "CI high"), type = "number")
)
if (rmst_tau > 0) summary_cols <- c(summary_cols, list(list(key = "rmst", label = sprintf("RMST (τ = %s)", format(rmst_tau)), type = "number"),
list(key = "rmst_se", label = "SE", type = "number")))
cs_publish(list(
method = "survival.km",
methodVersion = "1.0.1",
title = paste0("Kaplan–Meier survival", if (length(levels_g)) paste(" by", g) else ""),
engine = cs_engine_info("survival", "codesplashr"),
n = length(tt),
summary = paste0(sprintf("%d of %d subjects had the event (%s); median survival %s.", sum(ev), length(ev), event_label, med_text),
if (length(levels_g)) sprintf(" Log-rank %s.", cs_fmt_p(values$logrank_p)) else ""),
apa = paste0("median survival = ", med_text,
if (length(levels_g)) sprintf("; log-rank χ²(%d) = %s, %s", values$logrank_df, cs_fmt_num(values$logrank_chisq), cs_fmt_p(values$logrank_p)) else ""),
statistics = c(list(
list(key = "events", label = "Events", value = values$events, format = "integer"),
list(key = "median", label = "Median survival", value = values$median),
list(key = "median_ci", label = paste(pct, "CI"), value = c(values$median_low, values$median_high))
), if (length(levels_g)) list(list(key = "logrank_p", label = "Log-rank p", value = values$logrank_p, format = "p"))),
tables = list(
list(key = "summary", title = "Survival summary", columns = summary_cols, rows = summary_rows),
list(key = "survival_at", title = "Survival at chosen times", columns = list(
list(key = "group", label = if (length(levels_g)) g else "Curve", type = "string"), list(key = "time", label = "Time", type = "number"),
list(key = "n_risk", label = "At risk", type = "integer"), list(key = "surv", label = "Survival", type = "number"),
list(key = "lower", label = paste(pct, "CI low"), type = "number"), list(key = "upper", label = paste(pct, "CI high"), type = "number")
), rows = time_rows, note = paste(conf_type, "intervals; Greenwood standard errors."))
),
assumptions = assumptions,
warnings = warnings,
notes = list(sprintf("Event: %s. Intervals: %s transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).", event_label, conf_type)),
charts = list(cs_chart("km", "km-curve", paste0("Kaplan–Meier curve", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
low = cs_col("lower", curve$low, "numeric"), high = cs_col("upper", curve$high, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL,
nrisk = cs_col("At risk", curve$nrisk, "numeric"), ncensor = cs_col("Censored", curve$ncensor, "numeric")
)), cs_chart("cumhaz", "cumhaz", paste0("Cumulative hazard", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
)), cs_chart("loglog", "loglog-survival", paste0("Log–log survival", if (length(levels_g)) paste(" by", g) else ""), list(
time = cs_col(tcol, curve$time, "numeric"), surv = cs_col("Survival probability", curve$surv, "numeric"),
strata = if (length(levels_g)) cs_col(g, curve$strata, "categorical", levels = levels_g) else NULL
))),
values = values
))
median survival = 310; log-rank χ²(1) = 10.33, p = .001
- Events
- 165
- Median survival
- 310
- 95% CI
- [285, 363]
- Log-rank p
- .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-informative censoring — 63 of 228 observations are censored; censoring must be unrelated to prognosis.
- Number of events — At least 10 events per curve.
Survival summary
| sex | n | Events | Median | 95% CI low | 95% CI high | RMST (τ = 500) | SE |
|---|---|---|---|---|---|---|---|
| All | 228 | 165 | 310 | 285 | 363 | 310.33 | 11.246 |
| male | 138 | 112 | 270 | 212 | 310 | 278.76 | 14.355 |
| female | 90 | 53 | 426 | 348 | 550 | 360.91 | 16.801 |
Survival at chosen times
| sex | Time | At risk | Survival | 95% CI low | 95% CI high |
|---|---|---|---|---|---|
| All | 260 | 113 | 0.5967 | 0.5349 | 0.6656 |
| All | 510 | 41 | 0.2933 | 0.2320 | 0.3707 |
| All | 770 | 9 | 0.0881 | 0.0498 | 0.1560 |
| male | 260 | 61 | 0.5192 | 0.4409 | 0.6114 |
| male | 510 | 20 | 0.2232 | 0.1569 | 0.3176 |
| male | 770 | 7 | 0.0781 | 0.0390 | 0.1563 |
| female | 260 | 52 | 0.7186 | 0.6287 | 0.8214 |
| female | 510 | 21 | 0.4110 | 0.3050 | 0.5540 |
| female | 770 | 2 | 0.0832 | 0.0257 | 0.2697 |
log intervals; Greenwood standard errors.
- Event: status = 2. Intervals: log transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kaplan–Meier survival curves
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method survival.km 1.0.1 · spec 97d5cf030ef37e8c
# Dataset: lung (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import survival as sv # survfit/survdiff twins (see its docstring)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/lung.parquet", columns=["time", "status", "sex"])
n_input = len(df)
df["sex"] = pd.Categorical(df["sex"], categories=["male", "female"]) # stored level order
df = df.dropna(subset=["time", "status", "sex"]) # listwise deletion over the analysis columns
df["sex"] = df["sex"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["time", "status", "sex"]) # infinite values stop the run (registry/errors.yaml)
# %% Event coding
tcol = "time"
ecol = "status"
t = df[tcol].to_numpy(dtype=float)
if (t < 0).any():
cs.cs_error("CS_E_INVALID_VALUES", column=tcol, requirement="zero or positive (survival times)", count=int((t < 0).sum()))
codes = set(np.unique(df[ecol].to_numpy(dtype=float)).tolist())
if codes <= {0.0, 1.0}:
event_code = 1.0 # 0 = censored, 1 = event
elif codes <= {1.0, 2.0}:
event_code = 2.0 # 1 = censored, 2 = event (survival::Surv convention)
else:
raise ValueError(f"{ecol} must be coded 0/1 or 1/2 (the larger code is the event), or be a yes/no or categorical column")
ev = df[ecol].to_numpy(dtype=float) == event_code
event_label = f"{ecol} = {event_code:g}"
if not ev.any():
cs.cs_error("CS_E_NO_EVENTS", event=event_label)
# %% Kaplan–Meier
conf = 0.95
conf_type = "log" # pinned: survfit's default is "log"
times = [] or sv.default_times(t)
rmst_tau = 500 # 0 = no restricted mean
g = "sex"
levels = [str(x) for x in df[g].cat.categories]
gv = df[g].astype(str).to_numpy()
strata = [("All", np.ones(len(t), dtype=bool))] + [(lv, gv == lv) for lv in levels]
values = {"event_label": event_label, "n_groups": len(levels) if levels else None}
summary_rows, time_rows, curve = [], [], {"time": [], "surv": [], "low": [], "high": [], "strata": [], "nrisk": [], "ncensor": []}
for name, m in strata:
fit = sv.km(t[m], ev[m], conf=conf, conf_type=conf_type)
med, med_lo, med_hi = sv.km_median(fit)
rm, rm_se = sv.rmst(fit, rmst_tau) if rmst_tau > 0 else (None, None)
at = sv.km_at(fit, times)
nan = lambda x: None if x is None or not np.isfinite(x) else float(x) # noqa: E731
stats_ = {"n": float(m.sum()), "events": float(ev[m].sum()), "median": nan(med), "median_low": nan(med_lo),
"median_high": nan(med_hi), "rmst": nan(rm), "rmst_se": nan(rm_se)}
for k, v in stats_.items():
values[k if name == "All" else f"{k}[{name}]"] = v
summary_rows.append({"group": name, **stats_})
for i, x in enumerate(times):
key = f"{name}@{sv.key_num(x)}"
row = {"group": name, "time": x, "n_risk": float(at["n_risk"][i]), "surv": nan(at["surv"][i]),
"lower": nan(at["lower"][i]), "upper": nan(at["upper"][i])}
values[f"surv[{key}]"], values[f"surv_low[{key}]"], values[f"surv_high[{key}]"] = row["surv"], row["lower"], row["upper"]
values[f"n_risk[{key}]"] = row["n_risk"]
time_rows.append(row)
if (name == "All") == (not levels):
curve["time"] += [0.0] + fit["time"].tolist()
curve["surv"] += [1.0] + fit["surv"].tolist()
curve["low"] += [1.0] + [nan(x) for x in fit["lower"]]
curve["high"] += [1.0] + [nan(x) for x in fit["upper"]]
curve["strata"] += [name] * (len(fit["time"]) + 1)
curve["nrisk"] += [float(m.sum())] + fit["n_risk"].tolist()
curve["ncensor"] += [0.0] + fit["n_censor"].tolist()
# %% Log-rank test
if levels:
codes = np.array([levels.index(x) for x in gv])
lr = sv.logrank(t, ev, codes, rho=0.0) # survdiff(Surv(time, event) ~ group)
values.update({"logrank_chisq": lr["chisq"], "logrank_df": float(lr["df"]), "logrank_p": lr["p"]})
else:
values.update({"logrank_chisq": None, "logrank_df": None, "logrank_p": None})
# %% Assumptions
assumptions = [{"key": "censoring", "label": "Non-informative censoring", "status": "info",
"detail": f"{int((~ev).sum())} of {len(ev)} observations are censored; censoring must be unrelated to prognosis."}]
few = [r["group"] for r in summary_rows if r["events"] < 10 and (r["group"] != "All" or not levels)]
if few:
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "warn",
"detail": f"Fewer than 10 events in {', '.join(few)}; medians and curves are imprecise."})
else:
assumptions.append({"key": "sample_size", "label": "Number of events", "status": "pass", "detail": "At least 10 events per curve."})
# %% Result
pct = f"{conf:.0%}"
med_text = "not reached" if values["median"] is None else f"{values['median']:.4g}"
cs.publish({
"method": "survival.km",
"methodVersion": "1.0.1",
"title": "Kaplan–Meier survival" + (f" by {g}" if levels else ""),
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(len(t)),
"summary": f"{int(ev.sum())} of {len(t)} subjects had the event ({event_label}); median survival {med_text}."
+ (f" Log-rank {cs.fmt_p(values['logrank_p'])}." if levels else ""),
"apa": f"median survival = {med_text}" + (f"; log-rank χ²({values['logrank_df']:.0f}) = {cs.fmt_num(values['logrank_chisq'])}, {cs.fmt_p(values['logrank_p'])}" if levels else ""),
"statistics": [
{"key": "events", "label": "Events", "value": values["events"], "format": "integer"},
{"key": "median", "label": "Median survival", "value": values["median"]},
{"key": "median_ci", "label": f"{pct} CI", "value": [values["median_low"], values["median_high"]]},
] + ([{"key": "logrank_p", "label": "Log-rank p", "value": values["logrank_p"], "format": "p"}] if levels else []),
"tables": [
{"key": "summary", "title": "Survival summary", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
{"key": "events", "label": "Events", "type": "integer"}, {"key": "median", "label": "Median", "type": "number"},
{"key": "median_low", "label": f"{pct} CI low", "type": "number"}, {"key": "median_high", "label": f"{pct} CI high", "type": "number"},
] + ([{"key": "rmst", "label": f"RMST (τ = {rmst_tau:g})", "type": "number"}, {"key": "rmst_se", "label": "SE", "type": "number"}]
if rmst_tau > 0 else []), "rows": summary_rows},
{"key": "survival_at", "title": "Survival at chosen times", "columns": [
{"key": "group", "label": g if levels else "Curve", "type": "string"}, {"key": "time", "label": "Time", "type": "number"},
{"key": "n_risk", "label": "At risk", "type": "integer"}, {"key": "surv", "label": "Survival", "type": "number"},
{"key": "lower", "label": f"{pct} CI low", "type": "number"}, {"key": "upper", "label": f"{pct} CI high", "type": "number"},
], "rows": time_rows, "note": f"{conf_type} intervals; Greenwood standard errors."},
],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Event: {event_label}. Intervals: {conf_type} transformation (Greenwood SE); median limits from the interval curves (Brookmeyer–Crowley)."],
"charts": [cs.chart("km", "km-curve", "Kaplan–Meier curve" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"low": cs.col("lower", curve["low"], "numeric"), "high": cs.col("upper", curve["high"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
"nrisk": cs.col("At risk", curve["nrisk"], "numeric"), "ncensor": cs.col("Censored", curve["ncensor"], "numeric"),
}), cs.chart("cumhaz", "cumhaz", "Cumulative hazard" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
}), cs.chart("loglog", "loglog-survival", "Log–log survival" + (f" by {g}" if levels else ""), {
"time": cs.col(tcol, curve["time"], "numeric"), "surv": cs.col("Survival probability", curve["surv"], "numeric"),
"strata": cs.col(g, curve["strata"], "categorical", levels=levels) if levels else None,
})],
"values": values,
})
The option Restricted mean up to τ sets the horizon, and Report survival at times chooses the time points.
Check your understanding
CheckpointCheck yourself
Which statement is right?
Show the answer
Answer: b
A falling hazard means the curve falls more slowly, not that it rises. A hazard is a rate, so its value isn't limited to 1 and it isn't a probability.
Check yourself
Group A has a restricted mean of 300 days and group B of 270 days, with a horizon of 365 days. What does this mean?
Show the answer
Answer: b
The restricted mean describes the window up to the horizon and says nothing about what happens after it.
Check yourself
When should you choose the horizon ?
Show the answer
Answer: a
Picking where the gap looks largest inflates the difference, and a horizon past most patients' follow-up rests on very few people.
Recap
Recap- The hazard is the risk right now; the survival curve is what those risks add up to.
- The median needs the curve to cross 50%, which may never happen.
- Survival at fixed times and the restricted mean are well defined when the median isn't, and are easy to explain.
Concepts in this lesson