There's a book called "Event History Analysis with R" by G. Broström. But it provides minimal R code for whatever concepts are presented. I'd like to plot a hazard function, how do I do that? I want the exact same plots as given here. The plots shown are in this chapter. If possible, I'd like to do the same plots using ggplot2.
I've done survival and cumulative hazard plots using ggplot2 that look better, using the code:
library(survminer)
fit <- survfit(Surv(enter, exit, event) ~ male, data = df_final)
ggsurvplot(fit, title = "Survival Function") +
xlab("Age in years") +
ylab("Survival")
My data looks like this:
| id | male | enter | exit | event |
|---|---|---|---|---|
| 001 | 1 | 0.00 | 13.34 | 1 |
| 001 | 1 | 13.34 | 45.00 | 0 |
| 002 | 1 | 0.00 | 27.00 | 0 |
| 003 | 0 | 0.00 | 23.60 | 1 |
| 003 | 0 | 23.60 | 27.00 | 1 |
| 003 | 0 | 27.00 | 67.00 | 0 |
You can get the R codes to reproduce the figures in the book from the book's GitHub repo.
For example, for the figures you are trying to replicate you could copy and paste the basic data wrangling code from the repo and convert the base R plotting code to
ggplot2like so where I also made use of a bit ofdplyr,tidyrandpatchworkto combine the subplots: