【发布时间】:2019-11-13 15:03:41
【问题描述】:
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)。
【问题讨论】: