ggplot2 Transfer calculated value from smooth to linerange

Dear sir,
I have a problem about ggplot2.
I want to connect data point with ols result via vertical line, like The code listed below.
Can I transfer ..y.., the value calculated by stat_smooth, to geom_linerange directly?
I tried stat_smooth(...,geom="linerange",mapping(aes(ymin=pmin(myy,..y..),ymax=pmax(myy,..y..)) but it is not the result I want.
Thanks for any help.

library(ggplot2)
df<-data.frame(myx=1:10,myy=c(1:10)*5+2*rnorm(10,0,1))
lm.fit<-lm("myy~myx",data=df)
pred<-predict(lm.fit)
ggplot(df,aes(myx,myy))+geom_point()+geom_smooth(method="lm",se=FALSE)+
geom_linerange(mapping=aes(ymin=pmin(myy,pred),ymax=pmax(myy,pred)))

%E5%9B%BE%E7%89%87

It is not clear to me why the result is not what you want. I understand that you want a vertical line from each point to the fit line and that is what I see in your plot. Can you explain what you want to be different?
Here is another version of your code that is a little neater, in my opinion.

library(ggplot2)
suppressPackageStartupMessages(library(dplyr))
set.seed(1234)
df<-data.frame(myx=1:10,myy=c(1:10)*5+5*rnorm(10,0,1))
lm.fit<-lm("myy~myx",data=df)
df <- df %>% mutate(PredValue = predict(lm.fit))
df <- df %>% mutate(ymax = pmax(myy, PredValue), ymin = pmin(myy, PredValue))
ggplot(df,aes(myx,myy))+ geom_point()+ geom_smooth(method="lm",se=FALSE)+
  geom_linerange(mapping=aes(ymin=ymin,ymax=ymax))

Created on 2019-05-27 by the reprex package (v0.2.1)

Thanks for you help and reply.
The following code generate the same OLS fitted value:

1. predict(lm("myy~myx",data=df))
2. geom_smooth(mapping=aes(x=myx,y=myy),method="lm")

For the second code, I mean that ..y.. calculated by stat_smooth is the OLS fitted value.
To draw a vertical line, the OLS fitted value was calculated twice. Can I draw the vertical line Completely with ggplot only?

I cannot find a way to use the calculated values from geom_smooth in geom_linerange. If the main concern is to calculate the fit only once, I would store the predictions from the regression in the data frame and not use geom_smooth at all.

I modified my code a bit based on the answer you got on Stack Overflow.

library(ggplot2)
suppressPackageStartupMessages(library(dplyr))
set.seed(1234)
df<-data.frame(myx=1:10,myy=c(1:10)*5+5*rnorm(10,0,1))
lm.fit<-lm("myy~myx",data=df)
df <- df %>% mutate(PredValue = predict(lm.fit))
df <- df %>% mutate(ymax = PredValue, ymin = myy)
ggplot(df,aes(myx,myy))+ geom_point()+ geom_line(aes(y = PredValue))+
  geom_linerange(mapping=aes(ymin=ymin,ymax=ymax))

Created on 2019-05-28 by the reprex package (v0.2.1)

Thanks for you help and reply.
Maybe the best way is what you said. It is flexible and can be apply to any situation.
Thanks again.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.