R:将自定义n次多项式拟合到facet_wrap'中的每个facet;GGD图

R:将自定义n次多项式拟合到facet_wrap'中的每个facet;GGD图,r,ggplot2,linear-regression,curve-fitting,R,Ggplot2,Linear Regression,Curve Fitting,我试图将一个唯一的n次多项式拟合到刻面包装的ggplot中的每个刻面,但似乎无法实现这一点 可以对具有以下特征的所有面使用统一的1阶线性拟合: library(ggplot2) df <- diamonds polys <- c(2, 2, 2, 2, 2) custom.smooth <- function(formula, data,...) { smooth.call <- match.call() smooth.call[[1]] <- lm

我试图将一个唯一的n次多项式拟合到刻面包装的ggplot中的每个刻面,但似乎无法实现这一点

可以对具有以下特征的所有面使用统一的1阶线性拟合:

library(ggplot2)

df <- diamonds

polys <- c(2, 2, 2, 2, 2)

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') +
  stat_smooth(method='custom.smooth')
库(ggplot2)

df您可以分割数据,为每个面生成单独的平滑

# set up
library(ggplot2)

df <- diamonds
custom.smooth <- function(formula, data,...) {
  smooth.call <- match.call()
  smooth.call[[1]] <- lm
  eval.parent(smooth.call)
}
产生


mapply
使用一个函数应用于多个参数。首先定义了一个函数,它包含两个参数:1)数据,2)多项式次数。这与定义任何其他函数没有区别

function(dat, i) stat_smooth(data=dat, 
                             method='custom.smooth', 
                             formula=y~poly(x, i))  
然后,参数被定义为数据:原始数据被划分为每个方面中使用的数据,并定义度向量1到5(这可能是您的
polys
向量)


然后,这些参数通过dots参数传递给
mapply
,dots参数在每组参数上运行函数,以生成自动添加到面中的命名平滑列表。

这是您想要的吗<代码>ggplot(df,aes(x=克拉,y=价格))+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:长度(unique(df$cut)))
@user20650在我的RStudio中似乎没有呈现任何内容--是否缺少什么内容?duhaime,它在RStudio&r终端中以新的r会话呈现给我。GGV图3.0.0,R3.4。4@user20650我昨天重新启动了RStudio,没有爱,但今天重新启动系统会说“是的”,这正是我想要的!你能给出一个解释为什么mapply在这里得到dat和i参数的答案吗?如果是这样,我很乐意接受!
function(dat, i) stat_smooth(data=dat, 
                             method='custom.smooth', 
                             formula=y~poly(x, i))  
split(df, df$cut)
1:length(unique(df$cut))