[R] side by side boxplots
Dylan Beaudette
dylan.beaudette at gmail.com
Fri Nov 28 20:34:38 CET 2008
On Fri, Nov 28, 2008 at 10:55 AM, Phillip Porter <philnotfil at gmail.com> wrote:
> Good Morning,
> I am trying to get side by side boxplots of two groups on the same
> variable. The last item under ?boxplot led me to some useful code.
> I use "boxwex" to make the boxes narrower, "at" to shift them over
> and "add" to draw them both on the same graph. Something along the lines
> of:
>
> attach(group1)
> boxplot(Y~X, col="blue", boxwex=.4, at=1:n+.2)
> attach(group2)
> boxplot(Y~X, col="red", boxwex=.4, at=1:n-.2, add=TRUE)
>
> When I just make up a small dataset to try this out on it works
> great. My problem is that I don't have completely matching data in the real
> dataset. Every instance of the variable does not have data present from
> both groups. When they get put on top of each other they don't line up.
> Can I do something with my data to make it line up correctly using
> this approach? Is there another way of getting the same results?
>
> Thanks,
> Phillip
>
Without some data, it is hard to gauge what you are trying to
accomplish. You should probably have a look at some of the examples on
the boxplot manual page, and investigate the bwplot() function from
the lattice package.
In R, you need to have your data in what is called 'long-format' in
order to plot grouped data.
An example:
# two treatments
x <- rnorm(n=100, mean=1, sd=1)
y <- rnorm(n=100, mean=3, sd=2)
# an id vector
id <- rep(c(1,2), each=100)
# stack two treatments, and add id
d <- data.frame(treatment=c(x,y), id=factor(id) )
# plot:
boxplot(treatment ~ id, data=d)
# more fun with the lattice package:
# add another grouping vector
grp <- rep(c(1,2,3,4), each=25)
d <- data.frame(treatment=c(x,y), id=factor(id), grp=factor(grp) )
library(lattice)
bwplot(treatment ~ id | grp, data=d)
Cheers,
Dylan
More information about the R-help
mailing list