R. GGplot2,带自定义分位数的geom_boxplot

时间:2014-02-20 17:31:02

标签: r ggplot2

我有一个数据集,其中包括来自100个模拟列车运行的数据,这些模拟网络中有4列火车,6个站点和每个站点的每列火车到达时的迟到。我的数据看起来像这样:

MyData <- data.frame(
  Simulation = rep(sort(rep(1:100, 6)), 4),
  Train_number = sort(rep(c(100, 102, 104, 106), 100*6)), 
  Stations = rep(c("ST_1", "ST_2", "ST_3", "ST_4", "ST_5", "ST_6"), 100*4),
  Arrival_Lateness = c(rep(0, 60), rexp(40, 1), rep(0, 60), rexp(40, 2), rep(0, 60), rexp(40, 3), rep(0, 60), rexp(40, 5))
  )

现在,我需要创建一个类似于此的框图:

library(ggplot2)
m <- ggplot(MyData , aes(y = Arrival_Lateness, x = factor(Stations)))
m + geom_boxplot(aes(fill = factor(Train_number)))

https://imagizer.imageshack.us/v2/1144x436q90/19/bnrx.png

但这对我的数据不起作用,因为geom_boxplot使用四分位数范围的胡须。我想为盒子和胡须定义我自己的分位数。我从Stackoverflow发现了这篇文章,它部分地解决了我的问题Changing whisker definition in geom_boxplot。但是当我应用解决方案时(我通过将fill = factor(Train_number)插入到aes函数中来修改代码)我得到了这个:

f <- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

ggplot(MyData, aes(factor(Stations), Arrival_Lateness, fill = factor(Train_number))) + stat_summary(fun.data = f, geom="boxplot")

https://imagizer.imageshack.us/v2/1144x436q90/827/m9y0.png

这显然不是我想要的。我需要像第一张图像一样并排放置每列火车的箱子,而不是像第二张图片那样重叠。我该怎么做?

我将不胜感激任何帮助!

提前致谢!

1 个答案:

答案 0 :(得分:1)

如此接近:只需将position="dodge"添加到stat_summary(...)的调用中。

ggplot(MyData, aes(factor(Stations), Arrival_Lateness,fill=factor(Train_number))) + 
  stat_summary(fun.data = f, geom="boxplot",position="dodge")

ggplot是一个很棒的工具,但其中一个令人沮丧的事情是,默认值根据您使用的功能而有所不同。对于geom_boxplot(...),默认position"dodge",而对于stat_summary(...),默认position"identity"