Burton Guster
Burton Guster

Reputation: 2223

Trouble plotting predict line in R

I have a simple data set with two columns of data- K and SwStr.

K = c(.259, .215, .224, .223, .262, .233)
SwStr = c(.130, .117, .117, .114, .113, .111)

I plotted the data using:

plot(res$K, res$SwStr)

I want to plot the result of a linear model, using SwStr to predict K. I try to do that using:

graphic<-lm(K~SwStr-1, data=res)
P=predict(graphic)

plot(res$K, res$SwStr)
lines(P, lty="dashed", col="green", lwd=3)

But when I do this, I don't get any line plotted. What am I doing wrong?

Upvotes: 0

Views: 8430

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226087

(1) You are inverting the axes of the original plot. If you want SwStr on the x axis and K on the y axis you need

plot(res$SwStr, res$K)

or

with(res,plot(K~SwStr))

If you check the actual values of the plotted points on the graph, this might be obvious (especially if K and SwStr have different magnitudes) ...

For lm fits you can also use abline(graphic,...)

edit: (2) You also have to realize that predict gives just the predicted y values, not the x values. So you want something like this:

K=c(.259, .215, .224, .223, .262, .233)
SwStr=c(.130, .117, .117, .114, .113, .111)
g <- lm(K~SwStr-1)
par(las=1,bty="l")  ## my favourites
plot(K~SwStr)
P <- predict(g)
lines(SwStr,P)

Depending on the situation, you may also want to use the newdata argument to predict to specify a set of evenly spaced x values ...

Upvotes: 3

Related Questions