Soly
Soly

Reputation: 155

Labelling the legend in ggplot2 and ggfortify in R

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)

Upvotes: 3

Views: 8684

Answers (1)

cacti5
cacti5

Reputation: 2106

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

Upvotes: 6

Related Questions