11

I would like to plot multiple boxplots above/below each other instead of next to each other in R using ggplot2. Here is an example:

library("ggplot2")
set.seed(1)
plot_data<-data.frame(loc=c(rep(1,200),rep(2,100)),
                      value=c(rnorm(100,3,.5),rnorm(100,1,.25),2*runif(100)),
                      class=c(rep("A",100),rep("B",100),rep("C",100)))
ggplot(plot_data,aes(x=loc,y=value,group=class)) +
       geom_boxplot(fill=c("red","green","blue"))

This results in the following plot:

example plot

As you can see, the blue boxplot is centered around its loc value (2.0), while the red and green ones have only half the width and are plotted to the left and right of their shared loc value (1.0). I want to make both of them the same width as the blue one and plot them directly above each other.

How can I achieve this?

Note that I am sure that the boxplots won't overlap for the data I am going to visualize, just as they don't for the given example data.

mschilli
  • 1,884
  • 1
  • 26
  • 56

2 Answers2

14

Use position = "identity":

ggplot(plot_data,aes(x=loc,y=value,group=class)) +
       geom_boxplot(fill=c("red","green","blue"),position = "identity")

enter image description here

The default for geom_boxplot is to use position = "dodge".

mschilli
  • 1,884
  • 1
  • 26
  • 56
joran
  • 169,992
  • 32
  • 429
  • 468
4

The main discussion is: here

Briefly, one can use geom_boxplot(position=position_dodge(0)). One can specify the distance between the boxes varying 'position_dodge' value.

Community
  • 1
  • 1
Stan
  • 41
  • 1
  • While it reads less clearly as `position="identity"` (as [suggested](http://stackoverflow.com/a/17575793/2451238) by [@joran](http://stackoverflow.com/users/324364)), `position=position_dodge(0)` seems to be equivalent. – mschilli Oct 19 '15 at 09:11