Skip to content

Instantly share code, notes, and snippets.

@kaneplusplus
Created April 6, 2022 21:31
Show Gist options
  • Save kaneplusplus/2839ba6e9916fccff68fd16bbf056c43 to your computer and use it in GitHub Desktop.
Save kaneplusplus/2839ba6e9916fccff68fd16bbf056c43 to your computer and use it in GitHub Desktop.
Write a ggsurv object like you would a ggplot object.
library(survival)
library(survminer)
library(patchwork)
library(ggplot2)
ggsurvsave <- function(filename, plot = last_plot(), ...) {
if (!inherits(plot, "ggsurvplot")) {
stop("Argument plot does is not a ggsurvplot object.")
}
gsp <-
Reduce(
'/',
Filter(
function(x) inherits(x, "ggplot"),
plot
)
)
ggsave(filename = filename, plot = gsp, ...)
}
# Example usage:
fit <- survfit(Surv(time, status) ~ sex, data = lung)
gsp <- ggsurvplot(fit, data = lung, risk.table = TRUE)
# This doesn't work:
# ggsave("test_bad.svg", gsp)
# This does.
ggsurvsave("test_good.svg", gsp)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment