rbar-chartstacked-chart

space between groups on stacked grouped barchart


I want to be able to add space in between the groups on my grouped barchart in R. Usually I would use geom_bar(position = position_dodge(width = )) but I cannot use position = since it is already being used as position = "stack".

Is there a way around this issue?

enter image description here

I want to be able to add space between the Groups so increase space between capital A and B, B and C, etc.

I also would like to be able to change the colors and patterns of the stacked bars which I would usually use scale_fill_manual and geom_col_pattern but those will not work as they turn my plot back into one group.

set.seed(687532)                     # Create example data frame
data <- data.frame(facet = rep(LETTERS[1:5], each = 6),
                   group = c("x", "y"),
                   stack = letters[1:3],
                   value = round(abs(rnorm(30)), 2))
data  

ggplot(data,                         # Draw barplot with grouping & stacking
       aes(x = group,
           y = value,
           fill = stack)) + 
  geom_bar(stat = "identity",
           position = "stack", width = 0.6) + 
  theme_classic() + theme(panel.border = element_rect(colour = NA, fill=NA, size=0),
                          text = element_text(size = 8, family = "sans"),
  ) + scale_y_continuous(expand = c(0,0)) +  labs(x = "", y = expression(paste("Relative Abundance(%)"))) + 
  facet_wrap(~facet, strip.position = "bottom", scales = "free_x") +
  theme(panel.background = element_blank(),
        panel.spacing = unit(0, "line"), 
        strip.background = element_blank(),
        strip.placement = "outside") + theme(plot.title.position = 'plot', 
                                             plot.title = element_text(hjust = 0.5)) + theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust=1))

Solution

  • Since your groups are actually facets, just expand the x axis.

    ggplot(data, aes(x = group, y = value, fill = stack)) + 
      geom_col(position = "stack", width = 0.6) + 
      scale_y_continuous("Relative Abundance(%)", expand = c(0, 0)) +  
      scale_x_discrete(NULL, expand = c(0.5, 0.5)) +
      facet_wrap(~facet, strip.position = "bottom", scales = "free_x") +
      theme_classic() + 
      theme(panel.border = element_blank(),
            panel.background = element_blank(),
            panel.spacing = unit(0, "line"), 
            strip.background = element_blank(),
            strip.placement = "outside",
            axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1))
    

    enter image description here