gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 18:14:14 25 4
gpt4 key购买 nike

我想为每个因素(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)

enter image description here

最佳答案

每个 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)

Output

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

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)

Different lines per panel

关于r - 如何在R ggplot2中的geom_smooth(facet_wrap)中传递多个公式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71852716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com