R中的正常回归函数显示垂直线,而ggplot回归显示相关性?

时间:2018-07-25 07:32:41

标签: r ggplot2 regression linear

我正在绘制有关暴露于不同处理方法的幼虫密度的数据。我有两个采样日(第4天和第7天)。我一直在尝试进行线性回归,但在绘制时遇到了一些问题。

four <- read.csv("four.csv", header = T)

df1 <- structure(list(day = structure(c(1L, 1L, 1L, 1L), .Label = "four", class = "factor"), 
    treat = c(0L, 10L, 100L, 300L), dens = c(1.2, 1.6, 1.883333333, 
    1.216666667)), .Names = c("day", "treat", "dens"), class = "data.frame", row.names = c(NA, 
-4L))

mfour = lm(four$treat ~ four$dens)

plot(four$treat, four$dens)

abline(lm(four$treat ~ four$dens))

通过这段代码,我得到了-一条回归线似乎没有显示相关性:

beads <- read.csv("beads.csv", header = T)

df2 <- structure(list(day = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
                                        2L), .Label = c("four", "seven"), class = "factor"), treat = c(0L, 
                                                                                                       10L, 100L, 300L, 0L, 10L, 100L, 300L), dens = c(1.2, 1.6, 1.883333333, 
                                                                                                                                                       1.216666667, 1.833333333, 1.766666667, 1.4, 1.55)), .Names = c("day", 
                                                                                                                                                                                                                      "treat", "dens"), row.names = c(NA, 8L), class = "data.frame")

p1 <- ggplot(beads, aes(x=treat, y=dens, col=day)) + geom_point() +
  geom_smooth(method="lm", se=FALSE) +
  ylab("dens") +
  xlab("treat")
p1 <- p1 + theme_few() + 
  scale_colour_discrete(name="Day",
                        breaks=c("four", "seven"),
                        labels=c("Four", "Seven"))
p1

但是,当我使用ggplot时(因为我想将我的两个采样日都包括在同一图中的回归线),我得到的东西看起来像是相关的?

我很困惑为什么会这样..有人有任何想法吗? 预先感谢!

1 个答案:

答案 0 :(得分:0)

four<- structure(list(day = structure(c(1L, 1L, 1L, 1L), .Label = "four", class = "factor"), 
                      treat = c(0L, 10L, 100L, 300L), dens = c(1.2, 1.6, 1.883333333, 
                                                               1.216666667)), .Names = c("day", "treat", "dens"), class = "data.frame", row.names = c(NA, 
                                                                                                                                                      -4L))

您可以使用lm(y〜x)

plot(four$treat, four$dens)
abline(lm(four$dens~four$treat),col="green")

enter image description here

或从回归模型中读取系数

mfour = lm(four$dens ~ four$treat)
abline(coef = coef(mfour), col = "blue")

enter image description here

或使用lsfit(x,y)

abline(lsfit(four$treat , four$dens),col="red")
plot(four$treat, four$dens)

enter image description here