繁体   English   中英

来自未标记矩阵的 R 中的多个箱线图?

[英]Multiple boxplots in R from unlabelled matrix?

问题

我有一个 R 矩阵,其中包含一些由计算机程序生成的数据。 我已将数据配置为作为矩阵导入 R。 偶数列,列(2*i, 2*i+1)是在条件i下测量的两个变量。 我在下面对此进行了可视化,以及我如何尝试生成箱线图:

在此处输入图像描述


尝试

不幸的是,这些列没有任何标签或类似的东西,如果我有两列代表这种格式的不同标签,我不确定如何获得多个箱线图。

我试图使这个出色的问题适应工作,但鉴于他的列实际上是您在我的图表中看到的 (A,B) 对与 label 列的组合版本,我不确定如何重新处理它对于我的情况。


这是我到目前为止所得到的,但分组不存在,类别也不存在:

在此处输入图像描述

由于拥有实际数据很有用,因此我在此处发布了指向我的数据的链接。

您需要将数据从矩阵转换为数据框,并以某种方式提取有关组 (i) 和每个组中的第一/第二列的信息。

一个可能的解决方案:

library(tidyverse) # we'll use dplyr, ggplot2 and purrr
i = 3
n_cols_per_i = 2
mat <- matrix(1:(i*n_cols_per_i*9), ncol=n_cols_per_i * i)
# 3*2 columns of 9 values each

name_fn <- function(group, col){
  paste0('group_', group, '_col_', col)
}

colnames(mat) <- map2_chr(rep(1:i,n_cols_per_i), rep(c("A", "B"), i), name_fn)

df <- as_tibble(mat)

df <- df %>% pivot_longer(
  cols=everything(),
  names_to = c("group", "col"),
  names_pattern = "group_(.)_col_(.)"
  )

df %>% ggplot(aes(y=value, x=group, fill=col)) +
  geom_boxplot()

在此处输入图像描述

df将具有这样的结构,您也可以类似地应用链接问题中的其他图。

您可以沿条件向量对数据进行子集化。

(cond <- rep(LETTERS[1:2], ncol(d)/2))
# [1] "A" "B" "A" "B" "A" "B" "A" "B" "A" "B" "A" "B" "A" "B" "A" "B" "A" "B"

boxplot(d, boxfill=NA, border=NA, xaxt="n", xlim=c(0, 17.75),   ## initialize plot
        xlab="index", ylab="value", main="My plot")
boxplot(d[cond == "A"], xaxt="n", add=TRUE, boxfill=2,  ## subset A
        boxwex=0.35, at=which(cond == "A") - .25)
boxplot(d[cond == "B"], xaxt="n", add=TRUE, boxfill=4,  ## subset B
        boxwex=0.35, at=which(cond == "A") + .25)
## axis
axis(1, seq(ncol(d))[(seq(ncol(d)) + 1) %% 2 == 0], labels=1:(ncol(d)/2))
## optional legend
legend("topleft", leg=cond[1:2], pch=22, pt.bg=c(2, 4), col=1, bty="n")

在此处输入图像描述


数据:

d <- read.csv("https://gist.githubusercontent.com/Micrified/4bb8c392300998e99320bf5ec3ba3d01/raw/765baf87f8fe40ccd58c145d49a3c21ee6009de5/data.csv")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM