Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple boxplots grouped by two conditions

Tags:

r

boxplot

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
like image 938
Gongon Avatar asked Oct 29 '12 15:10

Gongon


People also ask

How do you make a boxplot with two groups in R?

Box plot for multiple groups In order to create a box plot by group in R you can pass a formula of the form y ~ x , being x a numerical variable and y a categoriacal variable to the boxplot function. You can pass the variables accessing the data from the data frame using the dollar sign or subsetting the data frame.

Can you make a boxplot with one variable?

To create a boxplot using ggplot2 for single variable without X−axis labels, we can use theme function and set the X−axis labels to blank as shown in the below example.


2 Answers

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)  
like image 124
kku Avatar answered Oct 26 '22 04:10

kku


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)
like image 2
dcarlson Avatar answered Oct 26 '22 04:10

dcarlson