将图例添加到ggplot [英] Adding legend to ggplot
本文介绍了将图例添加到ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这个问题是本文后续内容:上一篇文章
我有12个变量,M1,M2,...,M12 x 和 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)
$ c $
ggplot (data = df)+
geom_polygon(aes(x = model,y = a,group = 1),color =red,fill = NA)+
geom_polygon y = b,group = 1),color =blue,fill = NA)+
coord_polar()+
scale_y_continuous(限制=范围(水平),休息=水平,标签=水平)+
主题(axis.text.y = element_blank(),axis.ticks = element_blank(),axis.title.x = element_blank(),axis.title.y = element_blank())
我想添加一个图例到情节,我有两行,一个红色标记为a,一个蓝色标记为b。
我尝试使用 scale_colour_manual
如下:
scale_colour_manual(values = c(red,blue),labels = c(a,b))
但它似乎不起作用。任何帮助,将不胜感激。
解决方案
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,color = variable),fill = NA)+
scale_colour_manual(values = c(a=blue,b=red))+
coord_polar()+
scale_y_continuous(限制=范围(水平),休息=水平,标签=水平)+
主题(axis.text.y = element_blank(),axis.ticks = element_blank (),axis.title.x = element_blank(),axis.title.y = element_blank())
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())
这篇关于将图例添加到ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文