【发布时间】:2019-02-22 10:41:36
【问题描述】:
我有一个使用移动窗口计算中位数和 90% CI 的函数。因此,对于每个x = seq(xmin, xmax, by = wStep),我返回所有y 的中位数以及5% 和95% 的分位数,其x 的值小于wSize/2。我想通过创建自定义平滑函数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,这是我迄今为止提出的代码。但是,问题是这不显示功能区。也许我需要某种方式来声明这个自定义统计数据提供了美学 ymin 和 ymax。如何获取以下代码以输出与上述类似的结果?
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()中添加se = TRUE? -
@Z.Lin 这工作 O.o ...但我不明白为什么。为什么 GeomSmooth 会找到这个参数?例如,如果我在
moveWin函数的定义中添加一个参数se=FALSE,如果我调用stat_movingwindow(..., se = TRUE),它不会设置为true。为什么它会得到例如wStep的值?这两个参数都列在layer(... params= ...)调用中? -
请参阅下面的冗长(-winded)解释。我不认为我可以在评论部分的范围内解释这一点......