[英]Legend doesn't appear in ggplot with two different geom_line()
I have my data shown as below:我的数据如下所示:
library(ggplot2)
library(RColorBrewer)
Year_2012_2017 <- data.frame(a=c(5,4,2,5,4,6,6,12,7,7,6,3),
b=c(6,4,1,2,9,7,4,7,8,12,2,4),
c=c(1,1,6,4,5,7,11,14,10,6,7,8),
d=c(4,9,5,3,4,11,9,11,10,8,4,9),
e=c(4,4,5,3,1,19,10,11,19,8,7,9),
f=c(4,5,3,6,5,12,25,15,21,24,14,1))
Year_2012_2017$mean <- rowMeans(Year_2012_2017)
Year_2012_2017<- transform(Year_2012_2017, Min = pmin(a,b,c,d,e,f), Max = pmax(a,b,c,d,e,f), seq = seq_len(dim(Year_2012_2017)[1]))
Year_2018 <- data.frame(g=c(10,5,7,6,9,26,NA,NA,NA,NA,NA,NA))
Year_2018 <- data.frame(Year_2018,seq1 = seq_len(dim(Year_2018)[1]))
Month_name <- c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
And my graph code:我的图形代码:
ggplot(Year_2012_2017) +
geom_line(aes(factor(seq), mean), group = 1,size=1, color = brewer.pal(7, "Set1")[2],lty=2)+
#Mean of 2012 to 2017
geom_ribbon(aes(x = seq, ymax = Max, ymin = Min, fill= "Min-Max(2012-2017)"),alpha = 0.5)+
scale_fill_manual("",values="skyblue")+
#Min and max
geom_line(aes(Year_2018$seq1,Year_2018$g),group = 1,size=1, color = brewer.pal(7, "Set1")[2],lty=1)+
#Year of 2018
coord_fixed(ratio=1/6)+
xlab("Month") +
ylab("Number of case")+
scale_x_discrete(labels=Month_name)+
scale_y_continuous(limits = c(0, 30),breaks=seq(0,30,5))
Which produces the following graph:产生下图:
two lines and one ribbon两条线和一条丝带
I tried for quite a while but failed to add legend of two geom_line() , can anyone help me find the solution?我尝试了很长一段时间,但未能添加两个 geom_line() 的图例,谁能帮我找到解决方案? Thanks in advance :)
提前致谢 :)
Posting this for reference, but it is a direct application of this answer .发布此内容以供参考,但它是此答案的直接应用。 If you can't rearrange your data so that it's all in one dataframe with common columns, a workaround is to put labels in
aes()
and you will get a legend:如果您无法重新排列数据,使其全部位于具有公共列的数据框中,则一种解决方法是将标签放入
aes()
,您将获得一个图例:
ggplot(Year_2012_2017) +
geom_line(aes(factor(seq), mean, colour = "2012-2017"), group = 1,size=1, lty=2)+
#Mean of 2012 to 2017
geom_ribbon(aes(x = seq, ymax = Max, ymin = Min, fill= "Min-Max(2012-2017)"),alpha = 0.5)+
scale_fill_manual("",values="skyblue")+
#Min and max
geom_line(aes(Year_2018$seq1,Year_2018$g, colour = "2018"),group = 1,size=1, lty=1)+
#Year of 2018
coord_fixed(ratio=1/6)+
xlab("Month") +
ylab("Number of case")+
scale_x_discrete(labels=Month_name)+
scale_y_continuous(limits = c(0, 30),breaks=seq(0,30,5))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.