Adding linear model abline to log-log plot in ggplot

Viewed 8196

I cannot seem to replicate the adding of a linear abline to a log-log ggplot. Code below illustrates. Grateful for an idea where I'm going wrong.

d = data.frame(x = 100*sort(rlnorm(100)), y = 100*sort(rlnorm(100)))
(fit = lm(d$y ~ d$x))

# linear plot to check fit
ggplot(d, aes(x, y)) + geom_point() + geom_abline(intercept = coef(fit)[1], slope = coef(fit)[2], col='red')

# log-log base plot to replicate in ggplot (don't worry if fit line looks a bit off)
plot(d$x, d$y, log='xy')
abline(fit, col='red', untf=TRUE)

# log-log ggplot
ggplot(d, aes(x, y)) + geom_point() + 
  geom_abline(intercept = coef(fit)[1], slope = coef(fit)[2], col='red') +
  scale_y_log10() + scale_x_log10()
2 Answers

If you run the regression in logs, fit the line, and the transform the scales, you can use geom_abline

d = data.frame(x = 100*sort(rlnorm(100)), y = 100*sort(rlnorm(100)))
(fit = lm(log(d$y) ~ log(d$x)))

p <- ggplot(d, aes(x, y)) + geom_point() +
    geom_abline(intercept = coef(fit)[1], slope = coef(fit)[2], col='red') +
    scale_y_continuous(trans=log_trans()) +
    scale_x_continuous(trans=log_trans())

enter image description here

Related