5
votes

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
2

2 Answers

6
votes

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
votes

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)