Hannah Weiss
Hannah Weiss

Reputation: 1

How to plot linear and inverse regression fit lines in R?

I am trying to plot both linear and inverse fit lines on a scatterplot. I have attempted a good number of things without success.

I have attempted using ggplot with smooth function specification, but the inverse line still totally looks like y=0. I've tried adding ablines, no luck. I have not had success using lm(y=1/x).

Upvotes: 0

Views: 1828

Answers (1)

maydin
maydin

Reputation: 3755

What I understand from the inverse fitted line is ;

y = a + bx

data <- data.frame("y"=mtcars$disp,"x"=mtcars$wt)

fit <-  lm(data$y ~  data$x)
fit_inverse <-  lm(data$y ~  I(1/data$x))

However, since the x axises are different (x and 1/x) , to put them on the same graph you must use different x axises. Otherwise, you need to plot them separately.

plot(data$x,data$y,col = "blue",bty="l",pch=20,ylab = "",xlab="")
lines(data$x,fitted(fit) ,type="l",lty = 29,col="blue") 
par(new = TRUE)
plot(1/data$x,data$y, xaxt = "n", yaxt = "n",col = "red", lty = 
2,bty="l",pch=10,ylab = "",xlab="")
lines(1/data$x,fitted(fit_inverse) ,type="l",lty = "29",col="red") 
axis(side = 3)
legend("top", c("Fitted", "Inverse Fitted"),col = c("blue", "red"), lty 
= c(29, 2))

enter image description here

Upvotes: 1

Related Questions