我的数据显示如下:
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")
我的图形代码:
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))
将产生以下图形:
我尝试了一段时间,但未能添加两个geom_line()的图例,有人可以帮助我找到解决方案吗?在此先感谢:)
答案 0 :(得分:1)
将此内容发布以供参考,但这是this answer的直接应用。如果您无法重新排列数据以使它们全部包含在具有公共列的数据框中,则一种解决方法是
将标签放在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))