custom bar distances in ggplot

It’s not clear exactly what you mean. I’m assuming you mean you have a discrete x axis variable and you wish to specify custom spacing between each bar. It’s possible to use position_jitter to get random spacing, though this also affects bar width and I’m guessing is not what you want.

I would probably handle this by using a numeric x scale and relabelling the axis with my factor levels:

library(ggplot2)

ggplot(data = data.frame(x = 1:10 + rep(c(0.1, -0.1), 5), y = sample(11:20))) + 
  geom_bar(aes(x, y, fill = factor(x)), color = "black", stat = "identity") +
  scale_x_continuous(breaks = 1:10 + rep(c(0.1, -0.1), 5), 
                     labels = LETTERS[1:10]) +
  guides(fill = guide_none())

enter image description here

Of course, we can only guess at what you really want since you didn’t provide a motivating example.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top