ToToRo
ToToRo

Reputation: 373

How ggplot2 shows two different regression lines with same y but different x

say I have the following code using basic plot function.

plot(mydata$x1,mydata$y,xlab="x1",ylab="y",type="n")

abline(lm(y~x1,data=mydata))`

abline(lm(y~x2,data=mydata),lty=2)'

This will show two regression lines in a single graph, one is y=p*x1, one is y=p*x2 (p are parameters)

since I am using different x for the same y, how can I show the two regression lines together using ggplot2? I tried to define two geom_smooth. But the results are not correct.

geom_smooth(aes(y=y,x=x1))+gemo_smooth(aes(y=y,x=x2))

Upvotes: 2

Views: 1542

Answers (1)

mnel
mnel

Reputation: 115392

  • Specify method='lm'
  • spell geom_smooth correctly.

The following works:

set.seed(1)
d <- data.frame(x1=runif(10),x2=runif(10),y=runif(10))
ggplot(d, aes(y=y)) + 
    geom_point(aes(x=x1)) + 
    geom_smooth(aes(x=x1),method='lm') +  
    geom_smooth(aes(x=x2),method='lm') 

enter image description here

Upvotes: 4

Related Questions