Roland
Roland

Reputation: 344

How to put different symbols in autoplot

I'm having some troubles with autoplot() in survival objects. I will take the below as example

library(ggplot2)
library(ggfortify)
library(survival)
    datalung <- lung
    fitlung<- survfit(Surv(time,status) ~ sex,type = "kaplan-meier",data=datalung)
    autoplot(fitlung,conf.int=FALSE,pVal=TRUE,pX=800)+scale_color_grey()

enter image description here

In the example above, sex 1 and 2 have different grey scales, with just 2 groups it's fine to see the different groups.

The real dataset that I'm using have 9 different groups, and is hard to see the differents curves with this grey scale. I can't use colours. What I'm looking for is a way to put symbols to different groups, but I can't find this parameter in autoplot.

The surv.linetype have the option solid and dashed, but it changes all curves with same pattern and I don't want it. Taking the lung data as example, I want to put different linetype for sex 1 and sex 2.

Upvotes: 2

Views: 2044

Answers (2)

romsdocs
romsdocs

Reputation: 68

Building on @aosmith's answer, you can keep some of the features of ggfortify::autoplot() by suppressing its surv.linetype and adding your lines manually. Although, you have to explicitly specify the labels or else each 'geom' gets its own set of labels.

autoplot(fitlung, surv.linetype = 'blank',
                      conf.int=FALSE, pVal=TRUE, pX=800) +
geom_step(aes(linetype=strata) ) +
scale_linetype_manual(values = c('solid', 'dotted'), 
    labels = c('sex1', 'sex2') ) +
scale_color_manual(values = c('black', 'black'), 
     labels = c('sex1', 'sex2') )

Upvotes: 2

aosmith
aosmith

Reputation: 36114

Looking through the function code usually helps me figure out what can and cannot be changed. You can look at the code for autoplot.survfit by running ggfortify:::autoplot.survfit in the Console.

Looking through that you'll see only the color aesthetic is used for groupings. I didn't see an easy way to change this, but you can easily follow the recipe in the function to make your own plot. While building your own plot takes a few more steps, it gives you a lot of flexibility.

For example, if you wanted to change the shape of the lines and points for each group you can fortify the model and then build the plot.

plot.data = fortify(fitlung, surv.connect = TRUE)

ggplot(plot.data, aes(time, surv, shape = strata)) +
    geom_step(aes(linetype = strata)) +
    geom_point(data = subset(plot.data, n.censor > 0)) +
    scale_y_continuous(labels = scales::percent)

Note that I only know of 6 line types; even if there were more they would be difficult to tell apart. Shapes aren't much better, although there are more of those.

Upvotes: 5

Related Questions