可以分割数据,为每个面生成单独的平滑。
# set up
library(ggplot2)
df <- diamonds
custom.smooth <- function(formula, data,...) {
smooth.call <- match.call()
smooth.call[[1]] <- lm
eval.parent(smooth.call)
}
运行函数
ggplot(df, aes(x=carat, y=price)) +
geom_point(alpha=0.1) +
facet_wrap(~cut, scales='free') +
mapply(function(dat, i)
stat_smooth(data=dat, method='custom.smooth', formula=y~poly(x, i)),
dat=split(df, df$cut), i=1:length(unique(df$cut)))
生产
mapply
接受一个函数以应用于多个参数。首先定义一个函数,它有两个参数:1)数据,2)多项式次数。这与定义任何其他函数没有区别
function(dat, i) stat_smooth(data=dat,
method='custom.smooth',
formula=y~poly(x, i))
然后,参数被定义为数据:原始数据被划分为每个方面中使用的数据,并定义一个度向量,1到5(这可能是您的
polys
split(df, df$cut)
1:length(unique(df$cut))
然后将这些参数传递给
映射层
,通过dots参数,该参数在每组参数上运行函数,以生成自动添加到facet的指定平滑列表。