簡體   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