Bio*_*eek 2 r curve-fitting poisson 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)
Run Code Online (Sandbox Code Playgroud)
每个 只能有一个公式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)
Run Code Online (Sandbox Code Playgroud)
或者你可以用来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)
Run Code Online (Sandbox Code Playgroud)
如果您希望每个面板有不同的行,那么您可以过滤每个面板的数据。这里我们使用一个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)
Run Code Online (Sandbox Code Playgroud)