我从here借用了此示例数据集:
# Load library
library(ggplot2)
# Load data
data(mtcars)
# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method="lm")
print(p)
在上面的代码中,所有方面的回归方法和公式均相同。如果要为构面(或面板)6指定公式,则可以从here使用以下代码:
# Smoothing function with different behaviour depending on the panel
custom.smooth <- function(formula, data,...){
smooth.call <- match.call()
if(as.numeric(unique(data$PANEL)) == 6) {
# Linear regression
smooth.call[[1]] <- quote(lm)
# Specify formula
smooth.call$formula <- as.formula("y ~ log(x)")
}else{
# Linear regression
smooth.call[[1]] <- quote(lm)
}
# Perform fit
eval.parent(smooth.call)
}
# Plot data with custom fitting function
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method = "custom.smooth", se = FALSE)
print(p)
现在,如果我想向这些方面添加回归方程式:
# Load library
library(ggpmisc)
p + stat_poly_eq(formula = y ~ x,aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse=TRUE,label.x.npc = "right")
然后,我应该怎么做才能指定面板6上显示的方程式和R2,它们可以匹配我之前指定的模型?参见下图,现在面板6具有自己的拟合模型,但是方程式标签没有。也许我们可以定义与ggplot2参数类似的函数?
最佳答案
您正在调用的custom.smooth
函数似乎包含将公式定义为"y ~ log(x)"
的行。因此,您还需要在您的stat_poly_eq
函数中指定此函数,从而指定线性外观方程的多项式形状(但实际上是对数形式)。
即加:
p + stat_poly_eq(formula = y ~ log(x),
aes(label = paste(..eq.label.., ..rr.label.., sep = "~~~")),
parse=TRUE,label.x.npc = "right")
关于r - 在ggplot2中使用stat_poly_eq为每个方面指定公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48381672/