Can I get boxplot notches in ggplot2?

我只是一个虾纸丫 提交于 2019-12-04 00:28:57
kohske

Update In addition to the options detailed below, version 0.9.0 of ggplot2 includes this feature in geom_boxplot. Examining ?geom_boxplot reveals a notch and notchwidth argument:

+ geom_boxplot(notch = TRUE, notchwidth = 0.5)

Not elegant graphics but here is an example:

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

you can change the apparence of CI bar by tweaking the arguments of stat_summary.

crossbar version:

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

It may be interesting that on the ggplot2-dev mailing list a post concerning notched box plots has been posted.

You can find the development page on github. The package may be installed via:

# install.packages("devtools")
library(devtools)
install_github("ggplot2")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!