【问题标题】:Unable to Plot Multiple lm Lines on ggplot in R无法在 R 中的 ggplot 上绘制多条 lm 线
【发布时间】:2019-11-27 20:23:55
【问题描述】:

我试图在 ggplot 上绘制多条 lm 线,但似乎没有一条线出现在上面。我无法对它做出正面或反面。我想绘制每条 lm 线——代表分类字段中的“中”、“高”和“低”——但甚至没有出现单一的线。有人可以指导我做错什么吗?

我已经尝试使用 geom_smooth() 和 stat_smooth() 函数以及每个函数的方法公式的不同定义,例如 (method = "lm", formula = variable ~ value) 但无济于事。

data1B = data.frame(B_1=c(561.5806, 585.9286, 597.4839), B_2=c(780.5758, 
800.8750, 754.8788), B_3=c(767.4545, 771.6250, 778.6471), B_4=c(868.3448, 
1062.4000, 1184.4242), data.SWASH_group=c("low", "medium", "low"))

library(dplyr)
library(reshape2)

library(ggplot2)

d <- melt(data1B, id.vars="data.SWASH_group")
View(d)

# Everything on the same plot
ggplot(d, aes(variable, value, col=variable)) + geom_smooth(method="lm")+
geom_point(aes(col=data.SWASH_group, size=2)) +  
stat_smooth()

我实现的结果如下:

我想要达到的结果是这样的:

注意:输出更密集,因为它有更多数据点要绘制,而不是我在示例中出于娱乐目的提供的稀疏数据点。此外,图中的每条 lm 线都代表一种类型的分类变量,例如此处更具体的“高”和“低”。

【问题讨论】:

    标签: r ggplot2 lm


    【解决方案1】:

    确保变量(低和中)被识别为组

    ggplot(d, aes(variable, value, col=variable, group=as.factor(variable)) +
    geom_point(aes(col=data.SWASH_group, size=2)) +  
    stat_smooth()
    

    【讨论】:

    • 做到了,但仍然没有成功。不过还是谢谢。
    • 原来这行得通,我只是输入了一个错误的变量。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-20
    • 2018-09-14
    • 1970-01-01
    • 2021-06-06
    • 2022-08-12
    相关资源
    最近更新 更多