How to remove spaces between grouped bar charts with unequal number of bars?

I created a grouped bar chart, see here bar chart, and I would like to have equal spacing between the groups (see red marks in the bar chart photo). The issue is that some categories don't have any values and thefore the number of bars within each group varies. I tried it with "width" and "position_dodge" but it is not giving me the result I want. Here is the code to create the barplot:

ggplot(data_max_nm_agripol, aes(sub_category, percent, fill=cluster)) + 
geom_bar(stat="identity", position = position_dodge2(width = 0.9, preserve = "single",reverse=T),
show.legend = T, width = 0.9)+
xlab("policy")+ ylab("Frequency")+
geom_text(aes(label=count) , position = position_dodge2(width = 0.9, preserve = "single", reverse=T), hjust=-0.4, vjust=0.3)+
coord_flip() +
scale_y_continuous(labels = ~ scales::percent(.x, accuracy = 1))+ 
theme(axis.title.x = element_text(colour = "black"),
    axis.title.y = element_text(colour = "#b47a62", size = 16, face = "bold"),
    axis.text.y = element_text(colour = "#b47a62", size = 8, face = "bold"))

Does anyone have a solution for this?

Thank you!


Try: Make x factor and use geom_col instead of geom_bar and use position_dodge(0.5) with width=0.5. Here is an example with the mtcars dataset:

library(tidyverse)

  ggplot(mtcars, aes(factor(carb), mpg, fill=factor(am))) + 
    geom_col(position = position_dodge2(width = 0.5, , preserve = "single", reverse=T),
             show.legend = T, width = 0.5)+
    xlab("policy")+ ylab("Frequency")+
    geom_text(aes(label=mpg) , 
              position = position_dodge2(width = 0.5, preserve = "single", reverse=T), hjust=-0.4, vjust=0.3)+
    coord_flip() +
    scale_y_continuous(labels = ~ scales::percent(.x, accuracy = 1))+ 
    theme(axis.title.x = element_text(colour = "black"),
          axis.title.y = element_text(colour = "#b47a62", size = 16, face = "bold"),
          axis.text.y = element_text(colour = "#b47a62", size = 8, face = "bold"))

enter image description here