我借用了这个示例数据集here https://stackoverflow.com/questions/44912496/geom-smooth-with-facet-grid-and-different-fitting-functions:
# 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 https://stackoverflow.com/questions/44930704/r-nls-not-picking-up-additional-arguments-when-used-in-custom-function-in-geom/44932146#44932146:
# 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")
那么我应该做什么,指定显示在上的方程和 R2panel 6,可以匹配我之前指定的型号吗?请参见下图,现在面板 6 有自己的拟合模型,但方程标签没有。也许我们可以定义一个与 ggplot2 参数类似的函数?