47

I'd like to add spaces between bars in ggplot2. This page offers one solution: http://www.streamreader.org/stats/questions/6204/how-to-increase-the-space-between-the-bars-in-a-bar-plot-in-ggplot2. Instead of using factor levels for the x-axis groupings, however, this solution creates a numeric sequence, x.seq, to manually place the bars and then scales them using the width() argument. width() doesn't work, however, when I use factor level groupings for the x-axis as in the example, below.

library(ggplot2)

Treatment <- rep(c('T','C'),each=2)
Gender <- rep(c('M','F'),2)
Response <- sample(1:100,4)
df <- data.frame(Treatment, Gender, Response)

hist <- ggplot(df, aes(x=Gender, y=Response, fill=Treatment, stat="identity"))
hist + geom_bar(position = "dodge") + scale_y_continuous(limits = c(0, 
    100), name = "") 

Does anyone know how to get the same effect as in the linked example, but while using factor level groupings?

dpel
  • 1,954
  • 1
  • 21
  • 31
aaron
  • 6,339
  • 12
  • 54
  • 80

1 Answers1

96

Is this what you want?

hist + geom_bar(width=0.4, position = position_dodge(width=0.5))
  • width in geom_bar determines the width of the bar.
  • width in position_dodge determines the position of each bar.

Probably you can easily understand their behavior after you play with them for a while.

enter image description here

kohske
  • 65,572
  • 8
  • 165
  • 155
  • 5
    `width` in `geom_histogram()` is deprecated in modern ggplot2 (>= 2.1.0). – krlmlr Apr 06 '16 at 00:55
  • 14
    what if I want to keep the bars per-group together (e.g. the 'C' and 'T' bars here) but want to change the spacing between groups ('M' and 'F' here)? – user5359531 Oct 12 '17 at 20:43
  • 2
    Regarding the question by user5359531, see here: https://stackoverflow.com/questions/51892875/how-to-increase-the-space-between-grouped-bars-in-ggplot2 – Kastany Mar 08 '19 at 09:50
  • 2
    As kohske didn't describe how they work: `width` in `geom_bar` is the width of x-axis bar groups. `width` in `position_dodge` is the width of bars within each x-axis group. A width of "1" means that bars/groups touch each other. Widths < 1 adds space between bars or between groups. – GMSL Jun 15 '20 at 08:54