我想为这些因素中的每一个(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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句