如何创建自定义 ggplot2 平滑统计(不仅仅是自定义 lm 或 glm 模型)

How to I create a custom ggplot2 smoothing stat (not just a custom lm or glm model)

我有一个函数可以使用移动 window 计算中位数和 90% CI。因此,对于每个 x = seq(xmin, xmax, by = wStep),我 return 所有 yx 值小于 wSize/2 的中位数和 5% 和 95% 分位数。我想通过创建自定义平滑函数 stat_movingwindow() 使用 ggplot2 将其显示为线条和色带。我可以使用 geom_smooth(data = ..., stat = "identity"):

创建我想要的结果
moveWin <- function(d, wSize = 0.5, wStep = 0.1, 
  f = function(x) quantile(x, prob = c(0.05,0.50,0.95), na.rm = TRUE)
){
  x <- seq(min(d$x), max(d$x), by = wStep)
  y <- matrix(NA, ncol = 3, nrow = length(x))
  for(i in seq_along(x)){
    y[i, ] <- f(d[abs(d$x - x[i]) < wSize/2, ]$y)
  }
  y <- as.tibble(y)
  colnames(y) <- c("ymin","y","ymax")
  y$x <- x
  return(as.tibble(y))
}

set.seed(123)
d <- tibble(
 x= sqrt(seq(0,1,length.out = 50))*10,
 y= rnorm(50)
)

ggplot(data = d) + aes(x = x, y = y) +
  geom_smooth(
    data    = function(d) moveWin(d, wSize = 1, wStep = 0.1), 
    mapping = aes(ymin = ymin, ymax= ymax),
    stat    = "identity") + 
  geom_point() + scale_x_continuous(breaks = 1:10)

在 Vignette Extending ggplot2 之后,这是我到目前为止想出的代码。然而,问题是这并没有显示功能区。也许我需要某种方式来声明此自定义统计数据提供了美学 yminymax。如何让下面的代码输出与上面类似的结果?

StatMovingWindow <- ggproto("StatMovingWindow", Stat,
  compute_group = function(data, scales, wSize, wStep, fun) {
    moveWin(data, wSize = wSize, wStep = wStep, f = fun)
  },

  required_aes = c("x", "y")
)
stat_movingwindow <- function(mapping = NULL, data = NULL, 
  fun = function(d) quantile(d, probs = c(0.05, 0.50, 0.95), na.rm = TRUE),
  wStep = 0.1, wSize = 1,
  geom = "smooth", position = "identity", show.legend = NA, inherit.aes = TRUE,
  ...
){
  layer(
    stat = StatMovingWindow, data = data, mapping = mapping, geom = geom, 
    position = position, show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(wStep = wStep, wSize = wSize, fun = fun, ...)
  )
}

ggplot(data = d) + aes(x = x, y = y) +
  stat_movingwindow(wStep = 0.1, wSize = 1) + 
  geom_point() + scale_x_continuous(breaks = 1:10)

在您的 stat_movingwindow 代码中,对应几何的行是 geom = "smooth":

stat_movingwindow <- function(mapping = NULL, data = NULL, 
  fun = function(d) quantile(d, probs = c(0.05, 0.50, 0.95), na.rm = TRUE),
  wStep = 0.1, wSize = 1,
  geom = "smooth", # <- look here
  position = "identity", show.legend = NA, inherit.aes = TRUE,
  ...
){
  layer(
    stat = StatMovingWindow, data = data, mapping = mapping, geom = geom, 
    position = position, show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(wStep = wStep, wSize = wSize, fun = fun, ...)
  )
}

检查 geom_smooth 的代码,我们看到它包含参数 se = TRUE,并使用 GeomSmooth 作为它的 geom:

> geom_smooth
function (mapping = NULL, data = NULL, stat = "smooth", position = "identity", 
    ..., method = "auto", formula = y ~ x, se = TRUE, # <- look here
    na.rm = FALSE, 
    show.legend = NA, inherit.aes = TRUE) 
{
    params <- list(na.rm = na.rm, se = se, ...)
    if (identical(stat, "smooth")) {
        params$method <- method
        params$formula <- formula
    }
    layer(data = data, mapping = mapping, stat = stat, geom = GeomSmooth, # <- and here
        position = position, show.legend = show.legend, inherit.aes = inherit.aes, 
        params = params)
}

深入研究 GeomSmooth,我们发现其 draw_group 函数(负责绘制平滑线)将 se = FALSE 作为其默认参数。

根据代码,如果 se == FALSEhas_ribbon 也将是 FALSE,即使 ymaxymin 都存在于您的数据中,谢谢到 StatMovingWindow$compute_group 函数。这反过来意味着 GeomLine$draw_panel(path, panel_params, coord) 的唯一结果将单独返回,没有 GeomRibbon$draw_group(ribbon, panel_params, coord).

> GeomSmooth$draw_group
<ggproto method>
  <Wrapper function>
    function (...) 
f(...)

  <Inner function (f)>
    function (data, panel_params, coord, se = FALSE) # <- look here
{
    ribbon <- transform(data, colour = NA)
    path <- transform(data, alpha = NA)
    has_ribbon <- se && !is.null(data$ymax) && !is.null(data$ymin) # <- and here
    gList(if (has_ribbon) GeomRibbon$draw_group(ribbon, panel_params, coord), 
          GeomLine$draw_panel(path, panel_params, coord))
}

简而言之,geom_smooth 的默认参数 se = TRUE 覆盖了 GeomSmooth$draw_group 中的默认行为(同样适用于 stat_smooth),我们应该这样做如果我们想获得相同的结果,在 stat_movingwindow 中也是如此。

如果您希望通常绘制色带,则可以将 se = TRUE 作为参数包含在 stat_movingwindow 的定义中。如果它是临时的,您可以在需要时将其包含在您的代码中。