Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spacing between boxplots in ggplot2

Tags:

r

ggplot2

I have been working with ggplot2 a lot over the past few weeks and was wondering if anyone could help me solve this problem I am having.

When I plot my boxplot my boxes are touching each other. I would like them to have a little bit of space between them. Is there a way to accomplish this? I am sure there is and I am just not seeing it.enter image description here

like image 704
Tim Avatar asked Jun 11 '13 15:06

Tim


1 Answers

Let's borrow the reproducible example provided by Kevin Ushey in this question:

set.seed(123)
dat <- data.frame( 
  x=rep( c(1, 2, 3, 4), times=25 ),
  y=rnorm(100), 
  gp=rep(1:2, each=50) 
)

p <- ggplot(dat, aes(x=factor(x), y=y))
p + geom_boxplot(aes(fill = factor(gp))) #example 1

enter image description here

Then, following the advice of Arun, I tested the (position = position_dodge(.)) but with geom_boxplot instead of geom_bar, and it worked.

In this case, it was not necessary to change the boxes width.

So, changing the last line of the above code to:

p + geom_boxplot(aes(fill = factor(gp)),position=position_dodge(1))

did the trick.

enter image description here

like image 149
Andre Silva Avatar answered Sep 17 '22 00:09

Andre Silva