Adding a legend to a scatter plot with a built-in line and prediction interval

I have this ggplot

ggplot(dt1, aes(x=x,y=y)) + geom_point(color="orange",shape=1, size=1.5) + stat_function(fun=function(x) 1.05+.65*sqrt(x)+.1*x, color="blue" ) + stat_function(fun=function(x) 1.05-.65*sqrt(x)+.1*x, color="blue" ) + stat_smooth(method="lm",formula="y~-1+x",fullrange=TRUE,se = FALSE, color="black") 

enter image description here

The data is simple:

 > str(dt1) 'data.frame': 1451 obs. of 2 variables: $ y: int 70 161 151 207 100 268 184 156 246 43 ... $ x: int 679 1818 1650 2325 992 2412 1830 1398 2207 495 ... 

Here is sample data:

 dt1 <- structure(list(y = c(70L, 161L, 151L, 207L, 100L, 268L, 184L, 156L, 246L, 43L, 125L, 135L, 45L, 93L, 88L, 162L, 131L, 143L, 227L, 177L, 124L, 203L, 243L, 193L, 182L, + 223L, 259L, 215L, 170L, 288L, 67L, 141L, 272L, 160L, 66L, 123L, 226L, 383L, 149L, 354L), x = c(679L, 1818L, 1650L, 2325L, 992L, 2412L, 1830L, 1398L, 2207L, 495L, 1071L, 1200L, 723L, 1162L, 1075L, 1431L, 1169L, 1665L, 2136L, 1402L, 896L, 1951L, 2222L, 1960L, 1601L,+ 1787L, 2277L, 1861L, 1432L, 2451L, 626L, 1292L, 2216L, 1499L, 766L, 906L, 2157L, 3419L, 1352L, 3346L)), .Names = c("y", "x"), row.names = c(NA, 40L), class = "data.frame") 

I would like to have a legend with the following three entries:

  • one for geom_point showing the correct point type
  • one for stat_smooth showing a black line
  • one for stat_function (i.e. one legend entry, not two) showing the blue line

How can i achieve this?

+2
r ggplot2
source share
2 answers

As it turns out, aesthetics is the key.

 ggplot(dt1, aes(x=x, y=y)) + geom_point(shape=1,size=1.5, aes(colour="Points",shape='Points', linetype='Points')) + stat_function(fun=function(x) 1.05+.65*sqrt(x)+.1*x, aes(colour="Fitted",shape="Fitted",linetype="Fitted")) + stat_function(fun=function(x) 1.05-.65*sqrt(x)+.1*x, aes(colour="Fitted",shape="Fitted",linetype="Fitted")) + stat_smooth(method="lm",formula="y~-1+x",fullrange=TRUE,se = FALSE, aes(colour="Smoothed",shape="Smoothed",linetype="Smoothed"))+ scale_colour_manual('',values=c("Points"="orange", "Smoothed"="black", "Fitted"="blue"))+ scale_shape_manual('',values=c("Points"=1,"Smoothed"=NA,"Fitted"=NA))+ scale_linetype_manual('',values=c("Points"=0,"Smoothed"=1,"Fitted"=1)) 

enter image description here See also:

@Andrie is here

@Earnest A here

+3
source share

This is not the best way, but if it were me, I would try something like this:

 par(new=TRUE) plot(500,360,pch=1,col="orange",size=1.5) text(500,350,"|") text(500,340,"|",col="blue") text(580,360,[text],pos=4) text(580,350,[text],pos=4) text(580,340,[text],pos=4) 

Good luck

0
source share

All Articles