geom_smooth 与 facet_grid 和不同的拟合函数

geom_smooth with facet_grid and different fitting functions

首先,为这个例子道歉,但我找不到更好的数据集来证明这个问题。希望这就足够了。假设我正在尝试从 mtcars 数据集中绘制一个传输(自动与手动)和齿轮数的小平面网格,绘制 mpg 与位移的关系,如下所示:

# 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()
print(p)

这给出了,

注意,我使用 geom_smooth 添加了一条趋势线,它默认使用黄土曲线。我可以使用 nls 作为方法拟合用户定义的函数而不是黄土曲线,然后说明一个公式,这很棒。但是是否可以为每个面拟合 不同 用户指定的曲线?例如,左上面板的线性回归和右下面板的衰减指数。这可能吗?还是我用锤子敲螺丝?

编辑: 给出了自定义(即用户定义的)拟合函数的解决方案 .

根据给出的建议 here,一个可能的解决方案是:

# Load library
library(ggplot2)

# Load data
data(mtcars)

# Vector of smoothing methods for each plot panel
meths <- c("loess","lm","lm","lm","lm","lm","lm")

# Smoothing function with different behaviour in the different plot panels
mysmooth <- function(formula,data,...){
   meth <- eval(parse(text=meths[unique(data$PANEL)]))
   x <- match.call()
   x[[1]] <- meth
   eval.parent(x)
}

# Plot data
p <- ggplot(mtcars,aes(x = disp, y = mpg)) + geom_point() + facet_grid(gear ~ am)
p <- p + geom_smooth(method="mysmooth")
print(p)