简体   繁体   中英

ggplot2 - Edit Legend

I am working on swimmers plot for a set of data. I am trying to color code each bar based on whether or not the patient is still on treatment. I have formatted it so that each bar is colored based on the if they are on or off treatment. How do I edit the legend so that I can change the title and specify "on treatment" or "off treatment" instead of 0 or 1?

Example data frame TonT1:

Patient ID        Time1(months)     On Treatment (1 for yes, 0 for no)
1                     6                    1
2                     4.7                  0
3                     2.3                  1
4                     9.7                  1

... etc.

My code is below:

ggplot(data=TonT1, 
aes(x=reorder(Patient.ID, Time1), y=Time1, fill = factor(Off.Treatment))) 
+ ylim(0,15) + ylab("Time on Therapy") + xlab("Patient ID") 
+ theme_classic() + geom_bar(stat="identity", width = 0.5)

Just specify the title for the fill.

dat <- data.frame("Patient ID" = c(1,2,3,4), "Time1" = c(6, 4.7, 2.3, 9.7), "Off.Treatment" = c(1,0,1,1))

ggplot(data=dat, 
       aes(x=reorder(Patient.ID, Time1), y=Time1, fill = factor(Off.Treatment))) + 
  ylim(0,15) + ylab("Time on Therapy") + xlab("Patient ID") + 
  theme_classic() + geom_bar(stat="identity", width = 0.5) +
  guides(fill = guide_legend(title = "On Treatment"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM