繁体   English   中英

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

[英]Confidence interval bands in ggplot2 when using stat_quantile?

我想将中值样条和相应的置信区间带添加到ggplot2散点图中。 我正在使用'quantreg'包 ,更具体地说是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中位样条

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附带的绘图功能不是非常灵活/非常适合我的需要。 是否有可能在ggplot2图中获得置信ggplot2 也许通过模仿quantreg使用的方法,或者只是从绘图中复制它们?

数据: pastebin

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

 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM