如何在 ggplot2 R 中对 stat_poly_eq(即方程和 R 平方值)使用 mapply?

How to use mapply on stat_poly_eq (i.e. equation and R-squared values) in ggplot2 R?

我正在尝试添加 R 平方方程,每个方程都有不同的公式。我在 p 上尝试了 mapply 函数建模,但没有任何反应。没有错误,但也没有显示方程。我还想在一行上绘制方程,在下一行绘制 Rsquared,我不知道在 stat_poly_eq.

中添加 \n 的确切位置
library(ggplot2)
library(ggpmisc)
set.seed(14)
df <- data.frame(
  var.test = c("T","T","T","T","M","M","M","M","A","A","A","A"),
  val.test = rnorm(12,8,5),
  x = c(1:12)
)

my.formula <- c(y~x + I(x^2), y~x, y~x + I(x^2))
ggplot(df, aes(x = x, y = val.test)) + 
  geom_point() +
  mapply(function(x, z) geom_smooth(method="glm", data=function(d) subset(d, var.test==z), formula = x, 
                                    method.args = list(family = "poisson"), color = "black" ), my.formula, c("A","M","T")) + facet_grid(.~var.test) + 
  mapply(function(x,z) stat_poly_eq(formula = x, aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),  parse = TRUE, size = 2.5, col = "black", data=function(d) subset(d, var.test==z),my.formula, c("A","M","T")))

您的代码的问题是错误的结束括号,即您将 my.formulac("A","M","T") 作为 stat_poly_eq 的参数。这就是为什么没有绘制任何标签,因为您什么都没有循环。

关于你的第二个问题。 TBMK 你不能在数学表达式中换行。解决这个问题的一种方法是通过两个单独的 stat_poly_eq 层添加方程和 R^2。

此外,我稍微简化了您的代码。没有必要有多个 mapply。一个就够了。您可以 return 多层,方法是将它们包裹在 list.

library(ggplot2)
library(ggpmisc)

ggplot(df, aes(x = x, y = val.test)) +
  geom_point() +
  mapply(function(x, z) {
    data <- subset(df, var.test == z)
    list(
      geom_smooth(
        method = "glm", data = data, formula = x,
        method.args = list(family = "poisson"), color = "black"
      ),
      stat_poly_eq(formula = x, aes(label = ..eq.label..), 
                   parse = TRUE, size = 2.5, col = "black", data = data, vjust = -0.1),
      stat_poly_eq(formula = x, aes(label = ..rr.label..), 
                   parse = TRUE, size = 2.5, col = "black", data = data, vjust = 1.1)
    )
  }, my.formula, c("A", "M", "T")) +
  facet_grid(. ~ var.test)