我正在尝试将一个独特的 n 次多项式拟合到 facet-wrapped ggplot 中的每个方面,但似乎无法让它发挥作用。
可以对所有方面使用统一的一阶线性拟合,具有以下条件:
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')
我想不通的是如何使用 polys
中的 ith<
整数作为 ith<
方面的多项式次数情节。
有谁知道如何实现这种行为?其他人可以提供的任何帮助将不胜感激!
最佳答案
您可以拆分数据,为每个面生成单独的平滑。
# 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))
然后这些参数通过点参数传递给 mapply
,它在每组参数上运行该函数,以生成一个命名的平滑列表,这些平滑列表会自动添加到构面。
关于R:将自定义 n 次多项式拟合到 facet_wrap'd ggplot 中的每个方面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53024537/