multiple boxplots grouped by two conditions

ぐ巨炮叔叔 提交于 2019-12-10 13:56:52

问题


I am having real trouble in making mutliple boxplots in single plot... I have five variables three are numeric and two are Factor. I want boxplot for all three numerical variables but grouped by the two Factor variable... The plot shoud have two groups each for Low and High with three boxes for MM, ND and BB. legends should contain the abbrevations for MM, ND and BB.

Group   Class   Sal Wal Daa
MM  Low 21  34  4
ND  Low 23  65  3
BB  High    21  34  2
MM  High    25  23  4
MM  High    23  23  5
MM  High    13  54  6
MM  High    56  32  4
MM  Low 34  13  3
ND  Low 12  35  7
ND  Low 34  34  2
ND  Low 54  54  1
ND  High    32  34  6
ND  High    43  32  7
BB  Low 54  13  3
BB  Low 12  56  2
BB  Low 45  34  6
BB  High    32  32  3
BB  High    13  12  2
BB  High    54  12  5

回答1:


If you want to have a separate group of boxplots for each numeric variable, you can use the interaction() function to group variables by Group and Class:

test.data <- data.frame(Sal=rnorm(100),
                        group=factor(sample(LETTERS[1:3], 100, replace=TRUE)),
                        class=factor(sample(c("low","high"), 100, replace=TRUE)))
boxplot(Sal ~ interaction(group,class), data=test.data)  



回答2:


You need to rearrange your data first:

dta <- read.table(text="Group   Class   Sal Wal Daa
    MM  Low 21  34  4
    ND  Low 23  65  3
    BB  High    21  34  2
    MM  High    25  23  4
    MM  High    23  23  5
    MM  High    13  54  6
    MM  High    56  32  4
    MM  Low 34  13  3
    ND  Low 12  35  7
    ND  Low 34  34  2
    ND  Low 54  54  1
    ND  High    32  34  6
    ND  High    43  32  7
    BB  Low 54  13  3
    BB  Low 12  56  2
    BB  Low 45  34  6
    BB  High    32  32  3
    BB  High    13  12  2
    BB  High    54  12  5", header=TRUE)
dtaLong <- stack(dta, select=cbind(Sal, Wal, Daa))  
dtaLong <- data.frame(dtaLong, dta[,1:2])

Now ind is a new factor identifying values from the three variables in the original data set.

library(lattice)
bwplot(values~ind | Group + Class, data=dtaLong)


来源:https://stackoverflow.com/questions/13124827/multiple-boxplots-grouped-by-two-conditions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!