Search code examples
rggplot2plotgeom-bar

plot slightly separated in-group bars with ggplot2 geom_bar()


Is there a way to have a little separation between each group bars made with grouped bar_plot()? Like having a bigger distance between different groups and small distance inside group bars, but not sticked one another.

Here the whole code:

### my DF generation
df.bar <- as.data.frame( cbind(
                                "diagnosis" = rep( names_DX, 2 ) ,
                                "number" = as.numeric(c(9,18,43,8,34,12,3,7,38,12,8,6)),
                                "status" = c(1,1,1,1,1,1,0,0,0,0,0,0)
                                ))
df.bar$diagnosis <- factor(df.bar$diagnosis,levels(df.bar$diagnosis)[c(1,5,6,2:4)]) #reorder levels for plot

### plot generation
p <-    ggplot(data = df.bar, aes(x = diagnosis, y = as.numeric(as.character(number)), fill = factor(status) )) +
            geom_bar(stat = "identity", position=position_dodge())+
            theme_bw()

my result:

sticked bars

what I'd like to get (ignore colors difference etc, only for the bars positions):

separated bars

Thanks in advance for any help!


Solution

  • You can adjust these with the width parameters of geom_bar and position_dodge.

    geom_bar's width controls how wide each individual bar is. If = 1, the bars will collectively be as wide as the whole x-axis. (Though there may be space between groups if the bars overlap with each group.)

    position_dodge's width controls how much space each group is given. If it's zero, the bars in each group will be fully overlapped. If it matches the geom_bar width, the bars in each group will be touching each other on the sides. If it's 1, the distance between groups will be the same as the distance inside each group.

    library(ggplot2)
    ggplot(data = df.bar, aes(x = diagnosis, y = as.numeric(as.character(number)), fill = factor(status) )) +
      geom_bar(stat = "identity",  width = 0.4,
               position=position_dodge(width = 0.5))+
      theme_bw()
    

    enter image description here