thomasp85 / patchwork

The Composer of ggplots
https://patchwork.data-imaginist.com
Other
2.47k stars 163 forks source link

Working with ggsurv plots #190

Closed traversc closed 4 years ago

traversc commented 4 years ago

ggsurv plots from the survminer package has become a standard for survival analyses.

Would it be possible to get patchwork working with it out of the box?

A reproducible example:

library(survival)
library(survminer)
library(ggplot2)
library(patchwork)

fit1 <- survfit(Surv(time, status) ~ trt, data = veteran)
g1 <- ggsurvplot(fit1, data = veteran)

fit2 <- survfit(Surv(time, status) ~ I(age > 60), data = veteran)
g2 <- ggsurvplot(fit2, data = veteran)

g1 + g2 + plot_layout(ncol = 2)
Error in p + e2 : non-numeric argument to binary operator
In addition: Warning message:
In `+.ggsurv`(g1, g2) : Incompatible methods ("+.gg", "+.ggsurv") for "+"
thomasp85 commented 4 years ago

It appears ggsurv also provides its own + method and isn't really a "standard" extension, so that is unfortunately a no...

If ggsurv provides some way of turning the plot into a gtable or grob (e.g. works with ggplotGrob()) you could convert it to that and add it, but other than that I don't know. Maybe reach out to the ggsurv developers and see if they are interested in making it behave more like a standard ggplot2 extension...

yonicd commented 4 years ago
> class(g1$plot)
[1] "gg"     "ggplot"
> class(g1$table)
[1] "gg"     "ggplot"

surv2patch <- function(p) (p$plot / p$table) + plot_layout(heights = c(3,1))

surv2patch(g1) | surv2patch(g2)
thomasggodfrey commented 1 year ago

The survminer package seems to create a bespoke object that is not fully ggplot2 compatible. But there's a newer package for plotting survival curves called ggsurvfit, which creates ggplot2 compatible objects, so you can add layers and adjust themes.

ggsurvfit creates a plot object of class "ggsurvfit" "gg" "ggplot" I found this doesn't work with patchwork, but if you manually reset the class prior to composing your plot in patchwork... class(plot_1) <- c("gg", "ggplot") class(plot_2) <- c("gg", "ggplot") class(plot_3) <- c("gg", "ggplot") ... that works.