我能否在ggplot2中获得箱形图缺口?

14

是的,我知道这个问题一直存在。我也在谷歌群组中找到了哈德利的答案,即ggplot2箱线图目前还没有缺口。所以我的问题有两个:这个情况是否有改变(是否已经有原生实现的缺口),如果没有,是否有什么方法可以解决这个问题。

我的意思是我并不需要缺口外观,通过某些适当放置在箱线图上另一层的阴影区域来表示置信区间,也会看起来很不错。

同时,我添加了一个截图,因为我听说一个图形问题没有图形就不完整。 enter image description here

2个回答

19

更新 除了下面详细介绍的选项之外,ggplot2 的 0.9.0 版本还在 geom_boxplot 中包含了此功能。查看 ?geom_boxplot 可以发现有 notchnotchwidth 参数:

+ geom_boxplot(notch = TRUE, notchwidth = 0.5)

这里提供的图形不太优美,但是下面是一个示例:

# confidence interval calculated by `boxplot.stats`
f <- function(x) {
    ans <- boxplot.stats(x)
    data.frame(ymin = ans$conf[1], ymax = ans$conf[2])
}

# overlay plot (upper panel below)
p <- ggplot(iris, aes(Species, Sepal.Length)) + geom_boxplot() +
  stat_summary(fun.data = f, geom = "linerange", colour = "skyblue", size = 5)
p

# base graphics (lower panel below)
boxplot(Sepal.Length ~ Species, data = iris, notch = TRUE)
你可以通过调整stat_summary的参数来改变 CI 条的外观。

enter image description here enter image description here

Crossbar版本:

f <- function(x) {
  ans <- boxplot.stats(x)
  data.frame(ymin = ans$conf[1], ymax = ans$conf[2], y = ans$stats[3])
}

p <- ggplot(iris, aes(Species, Sepal.Length)) + 
  geom_boxplot(width = 0.8) +
  stat_summary(fun.data = f, geom = "crossbar", 
    colour = NA, fill = "skyblue", width = 0.8, alpha = 0.5)
p

在此输入图片描述


不错!通过扩大天蓝色的矩形并可能在其中添加一些透明度,它将基本完美。非常感谢。 - Matt Bannert
嗯,我意识到在缩放图表时固定大小是一个问题。我们不能有更动态的大小吗? - Matt Bannert
更新了,我放了 Crossbar 的版本。 - kohske
这里显示的置信区间是多少?例如90或95%。 - Docconcoct
非常有帮助!感谢您的发布。 - oatmilkyway

3

有趣的是,在ggplot2-dev邮件列表上发布了一篇关于缺口箱形图的帖子。

您可以在github上找到开发页面。该程序包可通过以下方式安装:

# install.packages("devtools")
library(devtools)
install_github("ggplot2")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接