geom_smooth 与 facet_grid 和不同的拟合函数

Lyn*_*akr 6 r ggplot2 facet-grid

首先,为这个例子道歉,但我找不到更好的数据集来证明这个问题。希望,这就足够了。假设我正在尝试从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)
Run Code Online (Sandbox Code Playgroud)

这使,

在此处输入图片说明

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

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

Mar*_*dri 4

根据此处给出的建议,可能的解决方案是:

# 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述