Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

r - Adding linear model abline to log-log plot in ggplot

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()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you are plotting linear relationship between x and y, you can use geom_smooth() with method="lm".

ggplot(d, aes(x, y)) + geom_point() + geom_smooth(method="lm",se=FALSE)+
  scale_y_log10() + scale_x_log10()  

UPDATE

It seems that geom_abline() doesn't have argument untf=TRUE as for function abline().

Workaround would be to use geom_line() and new data frame in it that contains y values calculated using coefficients of your linear model or using function predict().

ggplot(d, aes(x, y)) + geom_point() + 
  geom_line(data=data.frame(x=d$x,y=coef(fit)[1]+coef(fit)[2]*d$x))+
  scale_y_log10() + scale_x_log10()

ggplot(d, aes(x, y)) + geom_point() + 
  geom_line(data=data.frame(x=d$x,y=predict(fit)))+
  scale_y_log10() + scale_x_log10()

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...