在ggplot中添加线性模型abline到log-log图 [英] Adding linear model abline to log-log plot in ggplot
本文介绍了在ggplot中添加线性模型abline到log-log图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我似乎无法复制将线性abline添加到log-log ggplot。下面的代码说明。感谢一个想法,我错了。
d = data.frame(x = 100 * sort(rlnorm(100 )),y = 100 * sort(rlnorm(100)))
(fit = lm(d $ y〜d $ x))
#检查拟合的线性图
ggplot(d,aes(x,y))+ geom_point()+ geom_abline(intercept = coef(fit)[1],slope = coef(fit)[2],col ='red')
#log-log base plot to ggplot in ggplot(不要担心,如果fit line看起来有点偏离)
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()
$ c $当您绘制x和y之间的线性关系时,您可以使用 $>
解决方案 geom_smooth()与 method =lm
。 ggplot(d,aes(x,y))+ geom_point()+ geom_smooth(method =lm,se = FALSE)+
s cale_y_log10()+ scale_x_log10()
UPDATE
对于函数 geom_abline()
没有参数 untf = TRUE
> abline()。
解决方法是使用 geom_line()
数据框中包含使用线性模型的系数或使用函数 predict()
计算的y值。
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()
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()
解决方案 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()
这篇关于在ggplot中添加线性模型abline到log-log图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文