Drawing 2D boxplots

2019-08-08 18:59发布

问题:

I have grouped data with, say, 2 parameters:

set.seed(1)
dat <- data.frame( xx=sample(10,9),
                   yy=sample(20,9),
                   group=c('A','B', 'C')  )

I can draw boxplots for each dimension:

ggplot(dat, aes(x=group, y=yy, fill=group)) + geom_boxplot() 
ggplot(dat, aes(x=group, y=xx, fill=group)) + geom_boxplot() + coord_flip()

Now I would to combine these and draw boxplots reflecting data on both variables, something like this: (this image was made manually in graphic editor)

Is there any easy way to draw this kind of boxplots?

回答1:

That is not good way of representation. It can be very confusing. Usually that data is represented like this.

datPlot <- melt(dat)
ggplot(datPlot, aes(x=group, y=value, fill=variable)) + geom_boxplot() 

or if the range of two variables is very different you can try faceting

ggplot(datPlot, aes(x=group, y=value, fill=group)) + geom_boxplot()
 +facet_wrap(~variable,scale="free_y")

or this

ggplot(dat, aes(x=xx, y=yy, color=group)) + geom_point(size=3) 



标签: r ggplot2