【问题标题】:r scatter plot and regression line issuesr 散点图和回归线问题
【发布时间】:2020-08-09 03:32:47
【问题描述】:

我正在尝试为该图创建回归线,为什么下面的代码不起作用?

这样做后,我需要创建一个带有标签的自定义图例:名为“实际”的黑点和名为“预测”的蓝色短划线(对应于线)

library(ggplot2)
d1 <- c(20,30,40,50,60,70)
d2 <- c(23, 32,41,53,60,69)

df <- data.frame(d1, d2)


ggplot(df,aes(x=d1,y=d2)) +
  geom_point(size=1.1)+
  geom_smooth(method = "glm", 
              method.args = list(family = "binomial"), 
              se = FALSE)  

【问题讨论】:

    标签: r


    【解决方案1】:

    由于图表中因变量的值范围不在 0 和 1 之间,因此在 geom_smooth() 中,族不能是二项式,正如来自 ggplot() 的错误消息所述:

    `geom_smooth()` using formula 'y ~ x'
    Warning message:
    Computation failed in `stat_smooth()`:
    y values must be 0 <= y <= 1 
    

    如果我们使用family= 的默认值,则会打印回归线。

    library(ggplot2)
    d1 <- c(20,30,40,50,60,70)
    d2 <- c(23, 32,41,53,60,69)
    
    df <- data.frame(d1, d2)
    
    
    ggplot(df,aes(x=d1,y=d2)) +
         geom_point(size=1.1)+
         geom_smooth(method = "glm", 
                     se = FALSE)  
    

    注释绘图的一种方法是添加回归线和 R^2 信息。我们可以使用ggpubr 包及其stat_regline_equation() 函数来做到这一点。

    library(ggpubr)
    ggscatter(df, x = "d1", y = "d2", add = "reg.line",
              add.params = list(color = "blue", fill = "lightgray")) +
         stat_cor(label.x = 3, label.y = 70) +
         stat_regline_equation(label.x = 3, label.y = 66)
    
     
    

    ...和输出:

    【讨论】:

    • @Achilles - 图例有助于根据第三个变量的值区分图表上的点子集。在您的问题提供的数据中,没有第三个变量,因此通过 ggpubr 包打印回归方程可能比包含另一个图例更有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2021-11-23
    • 1970-01-01
    • 2021-02-06
    • 2012-06-27
    • 1970-01-01
    相关资源
    最近更新 更多