我正在尝试添加 R 平方方程,每个方程都有不同的公式。我在先前的答案上尝试了 mapply 函数建模,但没有任何反应。没有错误,但也没有显示方程式。我还想在一行上绘制方程,在下一行绘制 Rsquared,我不知道在\n
stat_poly_eq 中的确切位置添加。
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.formula
和c("A","M","T")
作为stat_poly_eq
. 这就是为什么当你没有循环时没有绘制任何标签。
关于你的第二个问题。TBMK 你不能在数学表达式中换行。解决这个问题的一种方法是通过两个单独的stat_poly_eq
层添加方程和 R^2。
此外,我稍微简化了您的代码。没有必要有多个mapply
s。一个就足够了。您可以通过将多个图层包装在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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句