Search code examples
rggplot2geom-bar

How to adjust the gap between horizontal bars in R?


How can I reduce the distance between horizontally placed bars in a chart? In this way, I will be able to save space in an article with a page limit. As an example, I prepared the following code and screenshot.

The gaps I want to reduce are places in red.

library(ggplot2)
survey <- data.frame(fruit=c("Apple", "Banana", "Grapes", "Kiwi", "Orange", "Pears"),
                     people=c(40, 50, 30, 15, 35, 20),tur=c("A","B","A","B","B","A"))
ggplot(survey, aes(x=fruit, y=people)) +
    geom_col(show.legend = FALSE,width = 0.5)+
  facet_wrap(~tur, ncol = 2,scales = "free")+
    coord_flip()

Solution

  • Maybe aspect.ratio can help?

    I suspect the issue might be due to the plotting area of the device rather than ggplot, which seems to fill the device area.

    With revised data using facet_wrap you are back to using aspect.ratio

    ggplot(survey1, aes(x = fruit, y = people)) +
      geom_col(show.legend = FALSE, width = 0.9)+
      facet_wrap(~tur, ncol = 2, scales = "free")+
      coord_flip()+
      theme(aspect.ratio = 0.3)
    

    Perhaps the issue is understanding how you transfer the plots into your article.

    ggsave("skinny_plot.png", width = 150, height = 40, units = "mm")
    
    ggsave("skinny_plot.pdf", width = 150, height = 40, units = "mm")
    

    Which gives you:

    enter image description here

    data

    survey1 <- data.frame(fruit=c("Apple", "Banana", "Grapes", "Kiwi", "Orange", "Pears"),
                         people=c(40, 50, 30, 15, 35, 20),
                         tur=c("A","B","A","B","B","A"))
    
    

    Created on 2021-04-16 by the reprex package (v2.0.0)