Mayou
Mayou

Reputation: 8818

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!

Upvotes: 0

Views: 371

Answers (2)

jO.
jO.

Reputation: 3512

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.

Upvotes: 0

Roland
Roland

Reputation: 132706

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())

enter image description here

Upvotes: 2

Related Questions