Using 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")
我可以单独拟合 ANCOVAlm()
然后使用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)
I know ancova()
HH 包中的自动化绘图,但我并不真正关心点阵图形。所以我正在寻找一个ggplot()
以-为中心的解决方案。
library(HH)
ancova(y ~ x + A, data = df)
有没有一种方法可以使用来完成此操作ggplot()
?对于这个例子,A
有两个级别,但我遇到过 3、4 或更多级别的情况。这formula
论证geom_smooth()
似乎没有答案(据我所知)。