简体   繁体   中英

Adding legend to ggplot

This question is a follow-up to this post: previous post

I have 12 variables, M1, M2, ..., M12 , for which I compute certain statistics x and y .

 df = data.frame(model = factor(paste("M", 1:28, sep = ""), levels=paste("M", 1:28, sep = "")), a = runif(28, 1, 1.05), b = runif(28, 1, 1.05))

 levels = seq(0.8, 1.2, 0.05)

Here is the plot:

 ggplot(data=df) + 
   geom_polygon(aes(x=model, y=a, group=1), color = "red", fill = NA) + 
   geom_polygon(aes(x=model, y=b, group=1), color = "blue", fill = NA) +
   coord_polar() + 
   scale_y_continuous(limits=range(levels), breaks=levels, labels=levels) +
   theme(axis.text.y = element_blank(), axis.ticks = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank())

I would like to add a legend to the plot, where I have two lines, one red labeled "a", and one blue labeled "b".

I tried using scale_colour_manual as follows:

scale_colour_manual(values = c("red", "blue"), labels = c("a", "b"))

but it doesn't seem to work. Any help would be appreciated. Thanks!

library(reshape2)
df1 <- melt(df, id="model")

levels = seq(0.8, 1.2, 0.05)

ggplot(data=df1) + 
  geom_polygon(aes(x=model, y=value, group=variable, colour=variable), fill = NA) + 
  scale_colour_manual(values=c("a"="blue", "b"="red")) +
  coord_polar() + 
  scale_y_continuous(limits=range(levels), breaks=levels, labels=levels) +
  theme(axis.text.y = element_blank(), axis.ticks = element_blank(), axis.title.x = element_blank(), axis.title.y = element_blank())

在此输入图像描述

You can remove the background from the legend by adding:

+ theme(legend.background=element_rect(colour=NA) 

Don't forget to add an last closing parenthesis.

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