0

I have data of the form

x <- matrix(rnorm(600), nrow = 100, ncol = 6)
x <- cbind(x, c(rep(1, 50), rep(2, 50)))
colnames(x) <- c("a", "b", "c", "d", "e", "f", "group")

A boxplot (without the "outlying" dots) of each column can be made like this:

library(ggplot2)
x <- as.data.frame(x)
xmelt <- melt(x)
boxplot(data = xmelt, value~variable, outlwd = 0)

I would like to have a plot consisting of 6 groups of boxplots, grouped by "a", "b", ..., "f", where each group (e.g. "a") has the boxplots with the values of "a" for the different values of "group". This should be possible using ggplot2, but I keep getting errors. And as finishing touch the boxplots need to be coloured using the "group"-variable. Thus, above each letter "a", ..., "f" there is a group of 2 (or more if "group" takes on more different values") boxplots that take a color according to the "group" value.

Akkariz
  • 139
  • 8

1 Answers1

3

This is probably possible using base boxplot but much easier with ggplot2.

You can use reshape2::melt as you did, but specify group as id.vars, then put an aesthetic on the group

ggplot(melt(x, id.vars='group')) + 
  geom_boxplot(aes(variable, value, color=factor(group)), outlier.colour=NA)

image but with outliers

edited to add To remove outliers as in your boxplot call, use outlier.colour (per this answer). outlier.color also works, at least in ggplot2 2.1.0.

jaimedash
  • 2,683
  • 17
  • 30
  • That was surprisingly straightforward. Is it also possible to remove the "outlying" dots, like I did in the normal box plot function? – Akkariz May 17 '16 at 19:38
  • Wonderful, your edit has a small typo, outlier.color does not work for me, outlier.colour does. – Akkariz May 17 '16 at 20:06
  • thx. color actually works in (newer?) versions of ggplot but I edited – jaimedash May 17 '16 at 20:32