2
votes

I found that boxplot() produces plot with :

  • upper whisker = min(max(x), Q_3 + 1.5 * IQR)
  • lower whisker = max(min(x), Q_1 - 1.5 * IQR)
  • upper side = 1 quartile
  • middle = mean
  • bottom side = 3 quartile

I have a dataframe which head looks like this:

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

X1H 8 2 0 0 0 2 2 2 6  2  4  2  4  2  4  8  2  6  0 10  0  6  4  0  6  2  8  2  2  8  6  2  2  2  8

X2H 2 0 2 2 2 4 0 4 0  0  2  2  2  2  0  6  2  2  2  0  0  0  2  0  2  4  2  2  2  2  2  2  4  2  0

X3H 0 2 0 0 2 2 0 0 0  4  2  2  2  2  2  0  2  2  0  0  2  0  0  2  2  2  0  6  2  0  2  0  6  0  2

X4H 0 0 0 2 0 2 0 0 2  0  2  0  2  0  0  2  0  6  0  2  2  2  2  0  0  2  4  2  2  2  0  2  4  2  6

X5H 2 0 0 0 2 0 0 2 0  0  2  0  0  2  2  2  0  2  0  2  0  2  0  6  0  2  4  4  0  2  2  0  2  0  4

X6H 2 0 2 0 2 2 0 2 2  0  2  2  2  0  0  2  2  2  0  0  2  0  2  0  0  2  2  2  2  0  2  0  2  2  4

I would like to have a boxplot which for every column shows:

  • upper whisker = min
  • lower whisker = max
  • upper side = mean + standard deviation
  • middle = mean
  • bottom side = mean - standard deviation

so I found this, which work like a charm:

min.mean.sd.max <- function(x) {
  r <- c(min(x), mean(x) - sd(x), mean(x), mean(x) + sd(x), max(x))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

p1 <- ggplot(aes(y = value, x = factor(group)), data = mydata)

p1 <- p1 + stat_summary(fun.data = min.mean.sd.max, geom = "boxplot")

but in the second case dataframe looks like this:

       value group
1 0.56025153     1
2 0.88368829     1
3 0.06555686     1
4 0.44767630     1
5 0.90424061     2
6 0.96331650     2

so I don't know what to put inside aes() into ggplot in my case.

1
I find your example not easily reproducible. What is group? It is not contained in the data.frame. And please provide the output of dput(mydata). - Alex

1 Answers

0
votes

I created a dataframe below first.

> data
  X X1 X2 X3 X4
X1H  8  2  0  0
X2H  2  0  2  2
X3H  0  2  0  0
X4H  0  0  0  2
X5H  2  0  0  2
X6H  2  0  2  0

Then, reshaped it by using the melt function.

data.melt<-melt(data, id="X")

Given that you wanted to draw a boxplot with your own computations, I calculated mean, sd, min, max for each column

data.sum<-ddply(data.melt, .(variable), summarise,
         mean = mean(value),
         sd = sd(value),
         min = min(value),
         max = max(value))

Then, you can create a boxplot for each column with this code below.

ggplot(data.sum, aes(x=variable))+geom_boxplot(aes(ymin =min, lower = mean-sd, middle = mean, upper = mean+sd, ymax =max), stat="identity")

enter image description here