用ggplot约束stat_smooth中的斜率(绘图ANCOVA) [英] Constraining slope in stat_smooth with ggplot (plotting ANCOVA)

查看:99
本文介绍了用ggplot约束stat_smooth中的斜率(绘图ANCOVA)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Using ggplot(), I am trying to plot the results of an ANCOVA in which slopes of the two linear components are equal: i.e., lm(y ~ x + A). The default behavior for geom_smooth(method = "lm") is to plot separate slopes and intercepts for each level of each factor. For example, with two levels of 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")

我可以分别将ANCOVA与lm()配合,然后使用geom_abline()手动添加线.这种方法有很多缺点,例如使线超出数据范围并手动指定颜色.

I can fit the ANCOVA separately with lm() and then use geom_abline() to manually add the lines. This approach has a couple of drawbacks like having the lines extend beyond the range of the data and manually specify the colors.

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()为中心的解决方案.

I know ancova() in the HH package automates the plotting, but I don't really care for lattice graphics. So I am looking for a ggplot()-centric solution.

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

是否有使用ggplot()完成此操作的方法?对于此示例,A具有两个级别,但是我遇到的情况为3、4或更多级别. (据我所知)geom_smooth()formula参数似乎没有答案.

Is there a method to accomplish this using ggplot()? For this example, A has two levels, but I have situations with 3, 4, or more levels. The formula argument to geom_smooth() doesn't seem to have the answer (as far as I can tell).

推荐答案

出于完整性考虑,此方法有效:

For completeness, this works:

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

这篇关于用ggplot约束stat_smooth中的斜率(绘图ANCOVA)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆