ggplot How to Change the Width of one bar

Viewed 34

I created this small data frame to mimic the one I'm working with.

df <- data.frame( sex = c('male', 'female', 'female', 'female', 'male', 'male', 'female', 'male'),
                  food = c("hamburger", "hamburger", "pizza", 'pizza', 'hotdog', 'pizza', 'hamburger', 'pizza'))

When I make a grouped bar chart one of the bars takes up twice as much room because one of the variables is zero. How can I change the width of that single bar so it is the same as the others?

ggplot(df, aes(x = food, fill = sex)) + geom_bar(position = 'dodge')

bar chart

1 Answers

You can use position_dodge2 with preserve="single" to keep same width like this:

df <- data.frame( sex = c('male', 'female', 'female', 'female', 'male', 'male', 'female', 'male'),
                  food = c("hamburger", "hamburger", "pizza", 'pizza', 'hotdog', 'pizza', 'hamburger', 'pizza'))

library(ggplot2)
ggplot(df, aes(x = food, fill = sex)) + 
  geom_bar(position = position_dodge2(preserve = "single"))

Created on 2022-08-18 with reprex v2.0.2

Add padding = 0 to remove whitespace between bars:

ggplot(df, aes(x = food, fill = sex)) + 
  geom_bar(position = position_dodge2(padding = 0, preserve = "single"))

Created on 2022-08-18 with reprex v2.0.2

Related