Search code examples
rgeom-bar

geom_bar: custom spacing between bars in


I have a data set containing survey responses from many different regions in different countries. Using a bar chart, I want to show the number of respondents from each region, and visually group them together by country. I though I'd do that by manually adjusting the space between the bars in the chart. In other words, set a small space between regions of the same country, and then a jump before the next region from another country. Hope this makes sense.

When I google this, width and position_dodge come up a lot, but they don't seem suited for getting different spaces between different bars. Is there any way to do this without restructuring the data set?


Solution

  • It's hard to help you without your data, but maybe this is a good solution for you, providing a little space, but also conveying the information in a neat way:

    library(ggplot2)
    
    df <- data.frame(group = c('A', 'A', 'B', 'B', 'C', 'C', 'C', 'C', 'C'), 
                     member = c('A1', 'A2', 'B1', 'B2', 'C1', 'C2', 'C3', 'C4', 'C5'), 
                     value = c(10, 15, 11, 12, 20, 21, 22, 40, 30))
    
    ggplot(data = df,
           aes(member, value)) +
      geom_bar(stat="identity") + 
      facet_grid(~group, shrink = T, drop = T, scales = "free", space = "free")
    

    You can also manipulate the size of the space between the plots if you want using something like:

    + theme(panel.spacing = unit(50, "pt"))

    enter image description here