0

I've learnt to do this type of plots with r, and add this regression lines predicted from a model.

## Predict values of the model##
p11=predict(model.coh1, data.frame(COH=coh1, espajpe=1:4))
p12=predict(model.coh1, data.frame(COH=coh2, espaje=1:4))

p11
       1        2        3        4 
1.996689 2.419994 2.843298 3.266602 

p12

       1        2        3        4 
1.940247 2.414299 2.888351 3.362403 

##PLOT## 
plot(espapli~espaje, mydata)
lines(1:4,p11, col="red")
lines(1:4,p12, col="green")

Now, I would like to do something similar using ggplot, is that possible? That is, introducing a regression line for these particular values.

2
  • 1
    If you provide a reproducible example one could help you Commented Nov 13, 2015 at 0:30
  • Finally I was able to do what I wanted. Thanks anyway for your williness to help. :-) Commented Nov 13, 2015 at 15:52

2 Answers 2

1

@gennaroTedesco gives an answer using the built in smoothing method. I'm not sure that follows the OP. You can do this via geom_line

# example data
set.seed(2125)
x <- rnorm(100)
y <- 1 + 2.5 *x + rnorm(100, sd= 0.5)

lm1 <- lm(y~x)
x2 <- rnorm(100)
p1 <- predict(lm1, data.frame(x= x2), interval= "c")

library(ggplot2)

df <- data.frame(x= x2, yhat= p1[,1], lw= p1[,2], up= p1[,3])

# plot just the fitted points
ggplot(df, aes(x= x, y= yhat)) + geom_line()

# also plot the confidence interval
ggplot(df, aes(x= x, y= yhat)) + geom_line() +
  geom_line(aes(x= x, y= up, colour= "red")) +
  geom_line(aes(x= x, y= lw, colour= "red")) + 
  theme(legend.position= "none")

# only the last plot is shown

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot! This really hepled me to do what I wanted to do! :-)
0

As a general rule regression lines can be added to ggplot making use of the function geom_smooth. Please see full documentation here. If the values to be fitted are the same ones used in the general aesthetic, then

p <- ggplot(data, aes(x = x, y = y)
p <- p + geom_smooth(method = 'lm')

does the job. Otherwise you need to fully specify the set of data and the model in the geom_smooth aesthetics.

1 Comment

Thanks for your answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.