0

Lets say I have a stacked barplot like below:

library(ggplot2)
dfr <- data.frame(x=1:5,y=c(4,6,2,3,6,8,3,6,8,4),
       z=c("A","A","A","A","A","B","B","B","B","B"))

ggplot(dfr,aes(x=x,y=y,fill=z))+
  geom_bar(stat="identity")

barplot

I would like to group 1 and 2 together, and group 3,4,5 together. My idea is to have a wider gap between 2 and 3. Is it possible to pass in a custom gap vector like c(2,4,2,2) for the gaps. I do not want to use faceting for this purpose.

mindlessgreen
  • 11,059
  • 16
  • 68
  • 113
  • 1
    One stop-gap solution could be to add bars of height 0 where you need spaces, as mentioned here: http://stackoverflow.com/questions/30100500/specific-spaces-between-bars-in-a-barplot-ggplot2-r – shrgm Nov 16 '16 at 17:22
  • See [here](http://stackoverflow.com/questions/37795648/r-ggplot2-barplot-partial-semi-stack?noredirect=1&lq=1) and heeps of links therein. – Henrik Nov 16 '16 at 17:34

1 Answers1

0

This is a bit of a hack, but will get your desired result.

library(ggplot2)
dfr <- data.frame(x=1:5,y=c(4,6,2,3,6,8,3,6,8,4),
       z=c("A","A","A","A","A","B","B","B","B","B"))
dfr$x2 <- ifelse(dfr$x %in% 1:2, dfr$x, dfr$x+1)

ggplot(dfr,aes(x=x2,y=y,fill=z))+
  geom_bar(stat="identity") + 
  scale_x_continuous("x", breaks = c(1, 2, 4, 5, 6), labels = seq(1:5))

enter image description here

Brandon LeBeau
  • 331
  • 1
  • 4