user2847512
user2847512

Reputation: 23

making Boxplot with 3 variables in r

I want to make a boxplot in r but I struggle with grouping the boxplot by a third variable.

I want to have boxplots- all on one y-axes (score on a treatment outcome questionnaire), called HAMD)) -

for weeks 0-5 (called week)

and all twice for two treatment groups (called Treatment).

I made two boxplots with

boxplot(MP$HAMD ~ MP$week)

and six with

boxplot(MP$HAMD ~ MP$Treatment)

But now I want 12 boxplots together, each per week per treatment. How can I do this in r?

By all means thank you very much.

Upvotes: 2

Views: 22733

Answers (1)

Greg Snow
Greg Snow

Reputation: 49640

You can do this with the interaction function and Base graphics:

boxplot( HAMD ~ interaction(treatment,week), data=MP )
boxplot( HAMD ~ interaction(week,treatment), data=MP )
boxplot( HAMD ~ interaction(week,treatment), data=MP,
    at= c(1:6, 8:13) )

And here is one option using the lattice package:

library(lattice)
bwplot( HAMD ~ week|treatment, data=MP )
bwplot( HAMD ~ treatment|week, data=MP )
bwplot( HAMD ~ treatment|week, data=MP, layout=c(6,1) )

And an option using the ggplot2 package:

library(ggplot2)
p <- qplot(interaction(treatment,week), HAMD, data=MP, geom="boxplot")
p
p + aes(fill=week)

Upvotes: 4

Related Questions