5

我想将中值样条曲线和相应的置信区间带添加到ggplot2散点图中。我正在使用'quantreg'-package,更具体地说是rqss函数(Additive Quantile Regression Smoothing)。

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()

ggplot2中值样条

-packagequantreg自带绘图功能;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)

在此处输入图像描述

但是 -package 附带的绘图功能quantreg不是很灵活/很适合我的需要。是否有可能在ggplot2情节中获得置信带?也许通过模仿 -package 中使用的方法quantreg,或者只是从情节中复制它们?

数据:pastebin

4

1 回答 1

3

你几乎拥有它。你打电话时

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

该函数非常有用地返回绘制的数据。我们所做的就是抓取数据框。首先对您的函数进行小幅调整,以合理的方式返回数据

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)
于 2016-02-02T22:09:44.927 回答