[英]Add legend to geom_line() graph in r
我一直试图在我的 ggplot 中添加图例,但失败了。 我尝试了功能
scale_colour_manual()<\/code> ,但图例没有出现。
ggplot()+
geom_line(data=Summary,aes(y=Y1,x= X),colour="darkblue",size=1 )+
geom_line(data=Summary,aes(y=Y2,x= X),colour="red",size=1 )
如前所述,必须在美学中指定颜色才能有图例。 然而,美学中的颜色实际上只是一个标签,然后传递到其他层次。 可以使用scale_color_manual
设置自定义颜色,并且可以使用labs
修复图例标签。
ggplot(data=Summary)+
geom_line(mapping=aes(y=Y1,x= X,color="Y1"),size=1 ) +
geom_line(mapping=aes(y=Y2,x= X,color="Y2"),size=1) +
scale_color_manual(values = c(
'Y1' = 'darkblue',
'Y2' = 'red')) +
labs(color = 'Y series')
要提供仅使用单个geom
调用的更紧凑的答案:
ggplot2
真的比宽(多列)更喜欢长数据(键值对)。 这要求您在使用tidyr
或reshape2
类的包绘制数据之前转换数据。 通过这种方式,您可以在aes
调用中拥有一个表示颜色的变量,这将生成图例。
对于您的数据:
library(tidyr)
library(ggplot2)
plot_data <- gather(data, variable, value, -x)
ggplot(plot_data, aes(x = x, y = value, color = variable)) +
geom_line() +
scale_color_manual(values = c("firebrick", "dodgerblue"))
然后,您可以通过scale_color
系列助手自定义图例。
我有同样的问题并尝试了这些方法,但没有得到回应。 你知道问题是什么吗:
P<-ggplot(data=file11, aes(x = No.)) +
geom_line(aes(y = S1), colour="red",size=.6)+
geom_line(aes(y = S2), colour="magenta", alpha=.4)+
xlab("age")+ylab("gender")+
theme(legend.position="bottom")+
labs(title="group 1")+ theme_bw()+theme(plot.title=element_text(size=12,hjust=0.5,face="bold"))+
coord_flip()+ theme(aspect.ratio = 1)+ scale_x_reverse()+ theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+ theme(legend.background = element_rect(colour = 'black', fill = 'white', linetype='solid'))+ylim(0.2,.6)+ scale_color_manual(values = c("S1" = "red",
"S2" = "magenta"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.