将线性模型abline添加到ggplot中的log-log图中

 高档的干果ieb 发布于 2023-02-10 09:50

我似乎无法复制添加线性abline到log-log ggplot.下面的代码说明.感谢我出错的想法.

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()

Didzis Elfer.. 8

当你正在策划x和y之间的线性关系,你可以使用geom_smooth()method="lm".

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

UPDATE

似乎geom_abline()没有untf=TRUE关于功能的论据abline().

解决方法是使用geom_line()其中的新数据框,其中包含使用线性模型的系数或使用函数计算的y值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()

在此输入图像描述

1 个回答
  • 当你正在策划x和y之间的线性关系,你可以使用geom_smooth()method="lm".

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

    UPDATE

    似乎geom_abline()没有untf=TRUE关于功能的论据abline().

    解决方法是使用geom_line()其中的新数据框,其中包含使用线性模型的系数或使用函数计算的y值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()
    

    在此输入图像描述

    2023-02-10 09:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有