I am using Rstudio
. I am using ggsurv
function from GGally
package for drawing Kaplan-Meier curves for my data (for survival analysis), from tutorial here. I am using it instead of plot
because ggsurv
takes care of legends by itself.
As shown on the link, multiple curves are differentiated by color. I want to differentiate based on linetype. The tutorial does not seem to have any option for that. Following is my command:
surv1 <- survfit(Surv(DaysOfTreatment,Survived)~AgeOnFirstContactGroup)
print(ggsurv(surv1, lty.est = 3)+ ylim(0, 1))
lty.est=3
(or 2) gives same dashed lines for all the lines. I want differently dashed line for each line. Using lty=type
gives error:object 'type' not found
. And lty=type
would work in ggplot
but ggplot
does not directly deal with survfit
plots.
Please show me how to differentiate curves by linetype in either ggsurv
or simple plot
(although I would prefer ggsurv
because it takes care of legends)
From the documentation for ggsurv
lty.est: linetype of the survival curve(s). Vector length should be either 1 or equal to the number of strata.
So, to get a different line type for each stratum, set lty.est equal to a vector of the same length as the number of lines you are plotting, with each value corresponding to a different line type.
For example, using the lung data from the survival
package
library(GGally)
library(survival)
data(lung)
surv1 <- survfit(Surv(time,status) ~ sex, data = lung)
ggsurv(surv1, lty.est=c(1,2), surv.col = 1)
Gives the following plot
You can add ggplot themes or other ggplot elements to the plot too. For example, we can improve the appearance using the cowplot theme as follows
library(ggplot2)
library(cowplot)
ggsurv(surv1, lty.est=c(1,2), surv.col = 1) + theme_cowplot()
If you need to change the legend labels after differentiating by linetype, then you can do it this way
ggsurv(surv1, lty.est=c(1,2), surv.col = 1) +
guides(colour = FALSE) +
scale_linetype_discrete(name = 'Sex', breaks = c(1,2), labels = c('Male', 'Female'))