【问题标题】:Boxplot for each row of a data [closed]每行数据的箱线图[关闭]
【发布时间】:2015-01-14 11:47:11
【问题描述】:

我在 R 中工作。我有三个矩阵:d1、d2、d3,并希望从矩阵的每一行生成一个箱线图。像这样:boxplot(d1[1,], d2[1,], d3[1,])。

如何为矩阵的每一行自动生成图。我需要一个循环吗?应用功能可以帮助我吗?此外,在一个绘图窗口中绘制 12 个箱线图会很棒。 感谢您的帮助!

【问题讨论】:

  • 为什么不先“整理”数据呢?您为每个变量使用一行。

标签: r loops matrix boxplot


【解决方案1】:

这是我认为您想要的一个可重复的示例。假设你有三个 4x40 矩阵:

set.seed(1)
d1 <- matrix(rnorm(40), nrow = 4)
d2 <- matrix(rnorm(40), nrow = 4)
d3 <- matrix(rnorm(40), nrow = 4)

您应该首先组织您的数据,例如堆叠它们并添加一列:

d <- rbind(t(d1), t(d2), t(d3))
d <- cbind(d, rep(1:3, each = 10))

现在您可以绘制前三个列的箱线图:

boxplot(d[, 1] ~ d[, 5])

如果您希望每个矩阵有四个,您可以使用循环:

par(mfrow=c(4,1))
for (i in 1:4){
  boxplot(d[, i] ~ d[, 5])  
}
par(mfrow=c(1,1))

但是,如果您想要更令人印象深刻的图形,请尝试使用 lattice 或 ggplot2 包。

希望对你有帮助

【讨论】:

    【解决方案2】:

    你可以在转置矩阵上调用boxplot:

    # Create some faux data
    x <- matrix(rnorm(50), 5, 10, dimnames = list(LETTERS[1:5], letters[1:10]))
    
    # Transpose and plot
    boxplot(t(x), col = rainbow(5))
    

    【讨论】:

    • 不幸的是,这不是主要问题。我希望箱线图只包含每个矩阵的一行。所以对于地块 A:矩阵 A、B、C 的第 1 行。对于地​​块 B:矩阵 A、B、C 的 rwo 2 等等......我是否需要在该部分中有一个循环(将 boxplot(d1[1,], d2[1,], d3[1,]) 替换为 @ 987654325@) 我最终会得到 100 个绘图,这就是为什么我更愿意在一个绘图窗口中绘制 12 个绘图。
    • @user2978751 我有点误读了。正如其他人所展示的,制作 100 个箱线图很容易。但是正如您所暗示的那样,100 个地块很多——但我看不出您想如何将其放入 12 个地块中。我只看到两种可能性:(a)3 个带有 100 个盒子的地块,这是我在帖子中试图暗示的;(b)100 个带有 3 个盒子的地块。
    【解决方案3】:
    # your matrices (you have 5 variables and 20 observations per matrix, so you'll have to transpose)
    m1 <- matrix(rnorm(100), 5, 20)
    m2 <- matrix(rnorm(100), 5, 20)
    m3 <- matrix(rnorm(100), 5, 20)
    
    # tidy data
    library(reshape2)
    Df <- melt(list(data.frame(t(m1)), data.frame(t(m2)), data.frame(t(m3))))
    
    # boxplot
    library(ggplot2)
    ggplot(data = Df, aes(L1, value, color = factor(L1))) + geom_boxplot() + facet_wrap(~variable)
    

    【讨论】:

      猜你喜欢
      • 2022-11-17
      • 2021-11-12
      • 2012-08-07
      • 1970-01-01
      • 1970-01-01
      • 2016-11-19
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      相关资源
      最近更新 更多