-1

I want to reduce the spacing between bars BUT without increasing the width of said bars. I am using the geom_bar function in ggplot2.

Someone asked this same question some years ago and provided an example plot (ggplot2 : How to reduce the width AND the space between bars with geom_bar). However, no one ever came up with a satisfactory solution to this problem. I hope this time will be different!

Thank you all in advance.

Raquel.

Phil
  • 7,287
  • 3
  • 36
  • 66
Rachel A.
  • 1
  • 2

1 Answers1

2

Let's think this through logically, and use the following concrete example to demonstrate:

library(ggplot2)

df <- data.frame(label = c("A", "B", "C", "D"),
                 value = c(3, 1, 2, 5))

p <- ggplot(df, aes(label, value))

To make this fully reproducible, let us specify a drawing window size of 4 inches by 4 inches:

x11(width = 4, height = 4)

p + geom_col(width = 0.5, color = "black")

enter image description here

If we decrease the spacing between the bars but keep the bars themselves the same width, then it follows necessarily that the distance between the left edge of the leftmost bar and the right edge of the rightmost bar must get smaller. The most common way to achieve this would be to increase the width of the bars but shrink the plotting window by the same amount.

If we increase the bar size from 1/2 to 2/3 and decrease the plot width to 3 inches, the bar width will be exactly the same number of pixels wide but the spacing between them will be smaller:

x11(width = 3, height = 4)

p + geom_col(width = 2/3, color = "black")

enter image description here

You will notice that the plot is narrower, but that is going to be true however you achieve this.

You could instead keep the plot window the same size but increase the spacing on either side of the plot:

x11(width = 4, height = 4)

p + geom_col(width = 0.75, color = "black") +
  scale_x_discrete(expand = c(1, 0))

enter image description here

Or specify a co-ordinate ratio instead of changing your plot window size:

p + geom_col(width = 2/3, color = "black") +
  coord_fixed(1.2)

enter image description here

Or add large margins to the plot instead:

p + geom_col(width = 2/3, color = "black") +
  theme(plot.margin = margin(10, 50, 10, 50))

enter image description here

But all of these methods involve essentially the same thing: if you want the bars to be closer together but the bars to remain the same size, you have to make the plot narrower. The answer in the linked question does point this out, and I don't think it is unsatisfactory - it is a geometric necessity.

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87