R Adjusting space between bars after coord_flip() in ggplot

Viewed 302

I have created a chart with ggplot.

I have set the width of each bar, but I also want to set the spacing between the bars to a certain value (I want to reduce the spacing marked in red to 0.1, for example)? I know there are options like position_dodge, but that does not seem to work in combination with coord_flip().

In this related post it was suggested to use theme(aspect.ratio = .2), but this does not allow to additionally set the specific width of the bars.

Are there any suggestions to achieve this?

Code:

library(ggplot2)

set.seed(0)
numbers <- runif(5, 0, 10)
names <- LETTERS[seq(1, 5)]
df <- cbind.data.frame(names, numbers)

ggplot(data = df, aes(x = names, y = numbers)) +
  geom_bar(stat = "identity", fill = "blue", width = 0.30) +
  coord_flip()

enter image description here

2 Answers

I think the solution is in the combination of

  • the width argument of geom_bar() (which fills the space reserved for a bar)
  • and the aspect ratio argument of theme(), which squeezes the plot vertically, leading to 'small' bars.

With the following code:

library(ggplot2)
    ## your data
    set.seed(0)
    numbers <- runif(5, 0, 10)
    names <- LETTERS[seq(1, 5)]
    df <- cbind.data.frame(names, numbers)       ## corrected args
    
    ggplot(data = df, aes(x = names, y = numbers)) + 
      geom_bar(stat="identity", 
               fill = "blue", 
               width=0.9) +            ### increased
      theme(aspect.ratio = .2) +       ### aspect ratio added
      coord_flip()

you get the following graph:

enter image description here

I personally prefer to use the ggstance package to avoid messing around with coord_flip. you need to switch your x and y

library(ggplot2)
library(ggstance)

ggplot(df, aes(x = numbers, y = names)) +
  geom_colh(fill = "blue", width = 0.9)

Related