R:将自定义 n 次多项式拟合到 facet_wrap'd ggplot 中的每个方面

标签 r ggplot2 linear-regression curve-fitting

我正在尝试将一个独特的 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)))

生产

enter image description here


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/

相关文章:

RNetLogo 不适用于 macOS Sierra 和 Windows

r - 如何在 R 中绘制用 kmeans 获得的簇的 3D 图?

r - 如何使用R在散点图上绘制R平方值?

python - 余弦波的贝叶斯拟合花费的时间比预期的要长

R:可以制作没有光泽的传单图和渲染表吗?

r - 在管道 %>% 之后插入 if 语句以在自定义函数中返回错误消息

r - 如何在 R ggplot 中设置用于不同组的形状?

r - ggplot : how to change colors of vertical lines according to group id (in polar plot)

python - 在 ols.param 中获取列名和系数的列表

r - 使用 foreach 循环和并行处理生成矩阵