Ana Inés
Ana Inés

Reputation: 1

Add regression lines from predictive values in ggplot

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.

Upvotes: 0

Views: 667

Answers (2)

alexwhitworth
alexwhitworth

Reputation: 4907

@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

Upvotes: 1

gented
gented

Reputation: 1707

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.

Upvotes: 0

Related Questions