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

问题描述 投票:-1回答:1

我想要做的是仅从我的原始数据框的某些值创建几个箱图(全部显示在单个箱图中)。

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

所以现在我希望R可视化参数〜站(参数是绿色的所有变量,站是“站点ID”)有没有办法告诉R我想要所有我的参数在x轴上仅适用于BB0028,例如,这意味着我只在箱图中考虑了mean_area,mean_area_exc,esd,feret,min和max的前6个值?这看起来像这样: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

我希望你能用简单的代码来帮助我获得我的情节。

谢谢!干杯,梅尔

r boxplot
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.