I have created a scatterplot using ggplot2 in RStudio with the function annotate("rect".... to add a layer of colours based on another variable. I have been trying to add a legend for SO long by googling and trying different methods found on this site and others, including using geom_rect function but I cannot seem to get it to work fully. Please can anyone help me add a legend purely based on the shaded areas. See my plot:
This is my script so far:
ggplot(prpc_data,aes(x=age,y=total_proprioception))+
annotate("rect",xmin = 2, xmax = 9, ymin = -Inf, ymax = Inf, colour="blue", fill="blue",alpha = 0.15)+
annotate("rect",xmin=6,xmax=12,ymin=-Inf,ymax=Inf,colour="hotpink",fill="hotpink",alpha=0.15)+
annotate("rect",xmin=8,xmax=16,ymin=-Inf,ymax=Inf,colour="yellow",fill="yellow",alpha=0.2)+
geom_point(shape=21,size=2,colour="black",fill="cadetblue3")+
geom_smooth(method="loess",se=FALSE,colour="cadetblue")+
labs(x="Age (years)",y="Mean proprioception score (0-4)")+
coord_cartesian(ylim=c(0,4),xlim=c(2,16))+
scale_y_continuous(breaks=seq(0,4,0.5))+
scale_x_continuous(breaks=seq(2,16,2))+
theme_bw()
I would be very grateful for any help