如何仅通过选择数据框中的某些行来在一个中创建多框箱线图

时间:2019-03-02 13:16:17

标签: r boxplot

我想做的是仅根据原始数据帧的某些值创建多个箱形图(全部显示在一个箱形图中)。

我的数据框如下所示: enter image description here

所以现在我想让R可视化 Parameter〜Station (参数都是绿色的变量,Station是“ station id”) 是否有一种方法可以告诉R我想让我的所有参数都在例如 BB0028 的x轴上 ONLY ,这意味着我只接受了的前6个值在箱图中将 mean_area mean_area_exc,esd,feret,min和max 考虑在内? 看起来像这样: enter image description here

我尝试了一种非常复杂的方法,一个接一个地添加单个箱形图,但是我相信肯定有一种更简单的方法。 这是我尝试过的:

bb28 <- df[c(1:6),]

bb28area <- boxplot(bb28$mean_area ~ bb28$BBnr)
bb28area_exc <- boxplot(bb28$mean_area_exc ~ bb28$BBnr)
bb28esd <- boxplot(bb28$mean_esd ~ bb28$BBnr)
bb28feret <- boxplot(bb28$mean_feret ~ bb28$BBnr)
bb28min <- boxplot(bb28$mean_min ~ bb28$BBnr)
bb28max <- boxplot(bb28$mean_max ~ bb28$BBnr)

boxplot(bb28$mean_area ~ bb28$BBnr)
boxplot(bb28$mean_area_exc ~ bb28$BBnr, add=TRUE, at = 1:1+0.45)

它也不是很好看,因为在图中x轴无法适应新的箱形图,然后将其切断: enter image description here

我希望您可以通过简单的正确代码来帮助我,以获得我的情节。

谢谢! 干杯,梅尔

1 个答案:

答案 0 :(得分:0)

也许您正在寻找下面的功能multi.boxplot。它仅使用基数R。

数据。 首先,组成一个数据集,因为您还没有提供可复制粘贴的格式给我们。

set.seed(1234)

n <- 50
BBnr <- sort(sprintf("BB%04d", sample(28:30, n, TRUE)))
bb28 <- data.frame(col1 = 1:n, col2 = n:1, BBnr = BBnr)
tmp <- matrix(runif(3*n), ncol = 3)
colnames(tmp) <- paste("mean", c("this", "that", "other"), sep = "_")
bb28 <- cbind(bb28, tmp)
rm(BBnr, tmp)

代码。

multi.boxplot <- function(x, by, col=0, ...){
  x <- as.data.frame(x)
  uniq.by <- unique(by)
  len <- length(uniq.by) - 1
  n <- ncol(x)
  n1 <- n + 1
  col <- rep(col, n)[seq_len(n)]
  boxplot(x[[ 1 ]] ~ by, at = 0:len*n1 + 1,
          xlim = c(0, (len + 1)*n1), ylim = range(unlist(x)), xaxt = "n", col=col[1], ...)
  for(i in seq_len(n)[-1])
    boxplot(x[[i]] ~ by, at = 0:len*n1 + i, xaxt = "n", add = TRUE, col=col[i], ...)
  axis(1, at = 0:len*n1 + n1/2, labels = uniq.by, tick = TRUE)
}

inx <- grep("mean", names(bb28))
multi.boxplot(bb28[inx], by = bb28$BBnr, col = rainbow(length(inx)))

enter image description here