3

I plotted a graph and want to customize the legend of this plot. I will appreciate all help with this. Thanks!

library("survival")
library("ggplot2")
library("ggfortify")

data(lung)
lung$SurvObj <- with(lung, Surv(time, status == 2))
km.by.sex <- survfit(SurvObj ~ sex, data = lung, conf.type = "log-log")

gender.plot <- autoplot(km.by.sex)
gender.plot <- gender.plot + 
  ggtitle("Gender based Survival (1=male, 2=female)") +
  labs(x = "Time", y = "Survival Probability") 
print(gender.plot)
cacti5
  • 2,006
  • 2
  • 25
  • 33
Soly
  • 155
  • 1
  • 2
  • 9
  • 2
    what exactly would you like to customize? also, is `cancer.surv` a Surv object, ie `Surv(time,status)`? – shuckle Oct 17 '17 at 00:56
  • As mentioned by shuckle, some parts in your question seem to be missing. When I run your code, I get the following error: "Error in eval(expr, envir, enclos) : object 'cancer.surv' not found", so apparently you defined this object somewhere, but I don't see the code for it. About the legend: if you for instance want to set the title, as to me your question title suggests, you can try to add `+scale_fill_discrete(name = "new title")` as discussed [here](https://stackoverflow.com/questions/14622421/how-to-change-legend-title-in-ggplot). If you want something else, please elaborate. – 4rj4n Oct 17 '17 at 07:40

1 Answers1

6

I've had a similar issue with customizing the ggfortify plot - I am not exactly sure what this question is asking, but I am going to assume you want to customize the legend from the ggfortify's autoplot. To quickly answer this - autoplot can be manipulated using typical ggplot functions for customization because it is a ggplot object. This should be the method for modifying the legend, autoplot does not have its own library for this. See this closed issue for more info.

I have slightly edited your question to contain reproducible code using the survival analysis example found here. An example of customizing the plot (renaming the legend and color labels):

gender.plot <- autoplot(km.by.sex)
gender.plot <- gender.plot + 
  ggtitle("Gender based Survival") +
  labs(x = "Time", y = "Survival Probability") +
  guides(fill=FALSE) +
  labs(colour = "Gender") +
  scale_color_manual(labels = c("Male", "Female"), values = c(1, 2))
print(gender.plot)

enter image description here

cacti5
  • 2,006
  • 2
  • 25
  • 33