使用 stat_quantile 时 ggplot2 中的置信区间带?

Confidence interval bands in ggplot2 when using stat_quantile?

我想将中值样条和相应的置信区间带添加到 ggplot2 散点图。我正在使用 'quantreg'-package,更具体地说是 rqss 函数(附​​加分位数回归平滑)。

ggplot2 中,我可以添加中值样条,但不能添加置信区间带:

fig = ggplot(dd, aes(y = MeanEst, x = N, colour = factor(polarization)))
fig + stat_quantile(quantiles=0.5, formula = y ~ qss(x), method = "rqss") +
  geom_point()

quantreg-包自带绘图功能; plot.rqss。我可以在哪里添加置信区间 (bands=TRUE):

plot(1, type="n", xlab="", ylab="", xlim=c(2, 12), ylim=c(-3, 0)) # empty plot
plotfigs = function(df) {
  rqss_model = rqss(df$MeanEst ~ qss(df$N))
  plot(rqss_model, bands=TRUE, add=TRUE, rug=FALSE, jit=FALSE)
  return(NULL)
}
figures = lapply(split(dd, as.factor(dd$polarization)), plotfigs)

但是 quantreg-package 附带的 plot 函数不是很 flexible/well 适合我的需要。是否可以在 ggplot2 图中获得置信带?也许通过模仿 quantreg-package 中使用的方法,或者简单地从图中复制它们?

数据:pastebin.

你快搞定了。当你打电话

 plot(rqss_model, bands=TRUE, add=TRUE, rug=FALSE, jit=FALSE)

该函数非常有助于 return 绘制数据。我们所做的就是获取数据框。首先对您的函数进行微调,return 以合理的方式处理数据

plotfigs = function(df) {
  rqss_model = rqss(df$MeanEst ~ qss(df$N))
  band = plot(rqss_model, bands=TRUE, add=TRUE, rug=FALSE, jit=FALSE)
  data.frame(x=band[[1]]$x, low=band[[1]]$blo, high=band[[1]]$bhi, 
             pol=unique(df$polarization))
}

接下来调用函数并压缩

figures = lapply(split(dd, as.factor(dd$polarization)), plotfigs)
bands = Reduce("rbind", figures)

然后用geom_ribbon绘制

## We inherit y and color, so have to set them to NULL
fig + geom_ribbon(data=bands, 
                  aes(x=x, ymin=low, ymax=high, 
                  y=NULL, color=NULL, group=factor(pol)), 
                  alpha=0.3)