2017-07-04 29 views
2

首先,为这个例子道歉,但我找不到更好的数据集来证明问题。希望这足以。说我是试图使变速器的小网格(自动与手动),并从mtcars数据集齿轮数绘出MPG发生位移,像这样:带有facet_grid和不同拟合函数的geom_smooth

# 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) 

赋予,

enter image description here

请注意,我已经使用geom_smooth添加了趋势线,并默认使用黄土曲线。我可以使用用户定义的函数而不是黄土曲线,使用nls作为方法,然后陈述公式,这很好。但有可能适合不同的用户指定的每个方面的曲线?例如,左上方的线性回归和右下方的指数衰减。这可能吗?还是我用锤子来驱动螺丝?

EDIT: 一种用于自定义解决方案(即,用户定义的)拟合函数给出here

回答

2

下面给出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) 

enter image description here

+0

感谢您的答复,@Marco。非常感谢。我注意到在'meths'中你只能使用以前定义的方法。用户定义的方法也可以吗?你能提供一个关于'mysmooth'如何工作的解释吗?我猜'数据$ PANEL'是方面编号还是ID?看起来你正在创建一个命令在第一行(即方法)上执行,大概这是在最后一行执行的,但其他两行如何工作? – Lyngbakr

+0

好吧,所以我想我到了那里。 'match.call()'获取所有传递给'mysmooth'函数的参数,然后第一个参数(即'formula')被我们自己的公式替换,对吧?接下来,使用这个新公式执行该命令。那是对的吗? – Lyngbakr