简体   繁体   English

将图例添加到ggplot

[英]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 . 我有12个变量, M1,M2,...,M12 ,我为此计算某些统计xy

 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". 我想在情节中添加一个图例,其中我有两条线,一条红色标记为“a”,一条蓝色标记为“b”。

I tried using scale_colour_manual as follows: 我尝试使用scale_colour_manual如下:

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. 不要忘记添加最后一个右括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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