简体   繁体   English

R中的多个箱形图,同时按列和行将矩阵分组

[英]Multiple boxplots in R while grouping a matrix both by columns and rows

I am having trouble trying to figure out how to make a single figure containing multiple boxplots in R, while grouping my data frame/ matrix both by columns and rows. 我很难弄清楚如何在R中按列和行对数据框/矩阵进行分组时如何制作一个包含多个盒形图的图形。

I have a data frame in R with 10 rows and 500 columns. 我在R中有一个数据行,其中有10行500列。 The columns are separated into 2 groups(factors - 1's and 2's) and now I want to have a single figure containing two boxplots for each row of my data frame subject to the column groups. 列分为2组(因数-1和2),现在我想有一个单一的图形,其中包含我要根据列组进行数据框每一行的两个箱形图。

Ex. 例如

    M1 N2 O1 P2 Q1 R2      # [The 1's and 2's refer to my two column groups]
 A  10 11 12 13 14 15
 B  15 14 13 12 11 10 
 C  20 21 22 23 24 25
 D  25 24 23 22 21 20

So for the above example I would like to have a single figure with "4 boxplots pairs" for each row such that each boxplot pair will represent values corresponding to 1's and 2's factors of my column. 因此,对于上面的示例,我希望每行有一个带有“ 4个箱形图对”的图形,这样每个箱形图对将代表对应于我列的1和2因子的值。

Thanks in Advance !!! 提前致谢 !!!

Here on idea using reshape2 . 这里使用reshape2想法。 Since You have more columns than rows, it natural to work on the transpose. 由于您的列多于行,因此自然需要进行转置。

library(ggplot2)
library(reshape2)
dt <- read.table(text='
M1 N2 O1 P2 Q1 R2     
A  10 11 12 13 14 15
B  15 14 13 12 11 10 
C  20 21 22 23 24 25
D  25 24 23 22 21 20',header=TRUE)
dt.m <- melt(t(dt))
dt.m$Var1 <- gsub('[A-Z]','',dt.m$Var1)

Here 2 options to plot : 这里有两个选项可以绘制:

library(ggplot2)
library(gridExtra)
p1 <- ggplot(dt.m) +
   geom_boxplot(aes(x=Var2,y=value,fill=Var1))

p2 <- ggplot(dt.m) +
  geom_boxplot(aes(x=Var2,y=value,fill=Var2))+
  facet_grid(~Var1)

grid.arrange(p1,p2)

在此处输入图片说明

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

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