ggpmisc::stat_poly_eq
有一个选项output.type = "numeric"
允许获得拟合模型参数的估计值。下面是我尝试将它与facet_wrap
. 每个方面我得到不同R²
的结果,但两个方面的系数相同。我做错了什么,还是一个错误?
library(ggpmisc)
set.seed(4321)
x <- 1:100
y <- (x + x^2 + x^3) + rnorm(length(x), mean = 0, sd = mean(x^3) / 4)
my.data <- data.frame(x = x,
y = y,
group = c("A", "B"))
my.data[my.data$group=="A",]$y <- my.data[my.data$group=="A",]$y + 200000
formula <- y ~ poly(x, 1, raw = TRUE)
myformat <- "Intercept: %s\nSlope: %s\nR²: %s"
ggplot(my.data, aes(x, y)) +
facet_wrap(~ group) +
geom_point() +
geom_smooth(method = "lm", formula = formula) +
stat_poly_eq(formula = formula, output.type = "numeric",
mapping = aes(label =
sprintf(myformat,
formatC(stat(coef.ls)[[1]][[1, "Estimate"]]),
formatC(stat(coef.ls)[[1]][[2, "Estimate"]]),
formatC(stat(r.squared)))))
编辑
我们必须抓住面板编号。奇怪的是formatC(stat(as.integer(PANEL)))
返回每个方面的面板编号:
但是formatC(stat(coef.ls)[[stat(as.integer(PANEL))]][[1, "Estimate"]])
不起作用,因为这里PANEL = c(1,2)
.