Last active
December 8, 2017 19:13
-
-
Save markdanese/95cf655891c83bc0b305bd44d2019a64 to your computer and use it in GitHub Desktop.
Plot spline based coefficients from a coxph model from the survival package in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# based on https://cran.r-project.org/web/packages/survival/vignettes/splines.pdf from Terry Therneau | |
# start with termplot without the plot to return results for all coefficients in the model | |
# y is the object in which the coxph model results have been saved | |
d <- termplot(y, se = TRUE, plot = FALSE) | |
# takes the termplot object (tp_obj), a specific variable name from the model as a string (var_name), and outputs a plot | |
# allows user to pass an x-axis label and to restrict the input range (e.g., input_range = c(10,30) will restrict the values | |
# to 10-30 inclusive). Need to be careful that the range makes sense. | |
# base plot version | |
spline_plot <- function(tp_obj, var_name = "", var_label = var_name, input_range = NULL){ | |
dat <- tp_obj[[var_name]] | |
if(!is.null(input_range)){ | |
dat <- dat[dat$x >= input_range[1] & dat$x <= input_range[2], ] | |
} | |
matplot( | |
dat$x, | |
exp(dat$y + outer(dat$se, c(0, -1.96, 1.96), '*')), | |
log ='y', | |
type ='l', | |
lty = c(1,2,2), | |
col = 1, | |
xlab = var_label, | |
ylab = "Relative death rate") | |
} | |
# ggplot2 version | |
# edit scale_y_continuous breaks to set different y-axis values to be shown | |
# edit the geom color settings for different colors | |
# add title, subtitle, and/or caption to labs as needed | |
spline_plot_gg <- function(tp_obj, var_name = "", var_label = var_name, input_range = NULL){ | |
dat <- tp_obj[[var_name]] | |
if(!is.null(input_range)){ | |
dat <- dat[dat$x >= input_range[1] & dat$x <= input_range[2], ] | |
} | |
ggplot(dat, aes(x, exp(y))) + | |
geom_ribbon(aes(ymin = exp(y - 1.96 * se), ymax = exp(y + 1.96 * se)), fill = "lightgrey") + | |
geom_line(color = "black") + | |
scale_y_continuous(trans = "log", breaks = c(0.2, 0.5, 1, 1.5, 2, 3)) + | |
theme_bw() + | |
labs( | |
x = var_label, | |
y = "Relative death rate") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please feel free to use/adapt the above for any purpose. Thanks to Terry Therneau for providing the instructions in his vignette.