【问题标题】:Constraining slope in stat_smooth with ggplot (plotting ANCOVA)使用 ggplot 约束 stat_smooth 中的斜率(绘制 ANCOVA)
【发布时间】:2010-11-22 23:28:33
【问题描述】:

使用ggplot(),我试图绘制 ANCOVA 的结果,其中两个线性分量的斜率相等:即lm(y ~ x + A)。 geom_smooth(method = "lm") 的默认行为是为每个因子的每个水平绘制单独的斜率和截距。例如,有两个级别的A

library(ggplot2)
set.seed(1234)

n <- 20

x1 <- rnorm(n); x2 <- rnorm(n)
y1 <- 2 * x1 + rnorm(n)
y2 <- 3 * x2 + (2 + rnorm(n))
A <- as.factor(rep(c(1, 2), each = n))
df <- data.frame(x = c(x1, x2), y = c(y1, y2), A = A)

p <- ggplot(df, aes(x = x, y = y, color = A))
p + geom_point() + geom_smooth(method = "lm")

我可以用lm() 单独拟合ANCOVA,然后使用geom_abline() 手动添加行。这种方法有几个缺点,例如线条超出数据范围并手动指定颜色。

fm <- lm(y ~ x + A, data = df)
summary(fm)

a1 <- coef(fm)[1]
b <- coef(fm)[2]
a2 <- a1 + coef(fm)[3]

p + geom_point() + 
  geom_abline(intercept = a1, slope = b) + 
  geom_abline(intercept = a2, slope = b)

我知道 HH 包中的 ancova() 会自动进行绘图,但我并不真正关心格子图形。所以我正在寻找以ggplot() 为中心的解决方案。

library(HH)
ancova(y ~ x + A, data = df)

有没有使用ggplot() 的方法来完成此任务?对于此示例,A 有两个级别,但我有 3、4 或更多级别的情况。 geom_smooth() 的 formula 参数似乎没有答案(据我所知)。

【问题讨论】:

  • 简要 - 拟合模型,然后绘制 预测。 expand.grid 会有所帮助

标签: r plot ggplot2


【解决方案1】:

为了完整起见,这是可行的:

library(ggplot2)
set.seed(1234)

n <- 20

x1 <- rnorm(n); x2 <- rnorm(n)
y1 <- 2 * x1 + rnorm(n)
y2 <- 3 * x2 + (2 + rnorm(n))
A <- as.factor(rep(c(1, 2), each = n))
df <- data.frame(x = c(x1, x2), y = c(y1, y2), A = A)
fm <- lm(y ~ x + A, data = df)

p <- ggplot(data = cbind(df, pred = predict(fm)),
  aes(x = x, y = y, color = A))
p + geom_point() + geom_line(aes(y = pred))

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    相关资源
    最近更新 更多