Question

I have the following data:

someFactor = 500
x = c(1:250)
y = x^-.25 * someFactor

which I show in a double logarithmic plot:

plot(x, y, log="xy")

Now I "find out" the slope of the data using a linear model:

model = lm(log(y) ~ log(x))
model

which gives:

Call:
lm(formula = log(y) ~ log(x))

Coefficients:
(Intercept)       log(x)  
      6.215       -0.250  

Now I'd like to plot the linear regression as a red line, but abline does not work:

abline(model, col="red")

What is the easiest way to add a regression line to my plot?

Was it helpful?

Solution

lines(log(x), exp(predict(model, newdata=list(x=log(x)))) ,col="red")

The range of values for x plotted on the log-scale and for log(x) being used as the independent variable are actually quite different. This will give you the full range:

lines(x, exp(predict(model, newdata=list(x=x))) ,col="red")

enter image description here

OTHER TIPS

Your line is being plotted, you just can't see it in the window because the values are quite different. What is happening when you include the log='xy' argument is that the space underneath the plot (so to speak) is being distorted (stretched and/or compressed), nonetheless, the original numbers are still being used. (Imagine you are plotting these points by hand on graph paper; you are still marking a point where the faint blue graph lines for, say, (1,500) cross, but the graph paper has been continuously stretched such that the lines are not equally spaced anymore.) On the other hand, your model is using the transformed data.

You need to make your plot with the same transformed data as your model, and then simply re-mark your axes in a way that will be sufficiently intuitively accessible. This is a first try:

plot(log(x), log(y), axes=FALSE, xlab="X", ylab="Y")
box()
axis(side=1,     at=log(c(1,2, 10,20, 100,200)), 
             labels=c(    1,2, 10,20, 100,200))
axis(side=2,     at=log(c(125,135, 250,260, 350, 500)), 
             labels=c(    125,135, 250,260, 350, 500))
abline(model, col="red")

enter image description here

Instead of transforming the axes, plot the log-transformed x and y.

plot(log(x), log(y))
abline(model, col="red")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top