如何在 R ggplot2 中传递 geom_smooth (facet_wrap) 中的多个公式?

How to pass multiple formulae in geom_smooth (facet_wrap) in R ggplot2?

我想为每个因素拟合三个不同的函数 (var.test)。我尝试了以下方法,但出现错误 Warning messages: 1: Computation failed in stat_smooth():invalid formula。还有其他方法可以让多个公式一次被读取吗?

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,4,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() +
  geom_smooth(method="glm", formula = my.formula, 
              method.args = list(family = "poisson"), color = "black" ) + facet_grid(.~var.test)

每个 geom_smooth() 只能有一个公式。您需要添加三个不同的 geom_smooth 层。你可以手动做到这一点

ggplot(df, aes(x = x, y = val.test)) + 
  geom_point() +
  geom_smooth(method="glm", formula = my.formula[[1]], method.args = list(family = "poisson"), color = "black" ) + 
  geom_smooth(method="glm", formula = my.formula[[2]], method.args = list(family = "poisson"), color = "black" ) + 
  geom_smooth(method="glm", formula = my.formula[[3]], method.args = list(family = "poisson"), color = "black" ) + 
  facet_grid(.~var.test)

或者您可以使用lapply来帮助

ggplot(df, aes(x = x, y = val.test)) + 
  geom_point() +
  lapply(my.formula, function(x) geom_smooth(method="glm", formula = x, 
              method.args = list(family = "poisson"), color = "black" )) + 
  facet_grid(.~var.test)

如果您希望每个面板有不同的行,那么您可以为每个面板过滤数据。在这里,我们使用 mapply 帮助程序并对每一行的数据进行子集化。

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)