mrub
mrub

Reputation: 513

Add spacing between groups in a stacked bar plot

Suppose I have a bar plot with grouped bars. Bars have one large group and multiple very small groups. Group labels are on the groups. In order to increase readability, I want to introduce some amount of spacing between groups.

I created an example image with the following code and an image editor.

library(ggplot2)
g <- ggplot(mpg, aes(class))
g + geom_bar(aes(fill = drv)) + theme_void()

exploding bar chart

So far, I have only found answers regarding spacing between bars.

Upvotes: 3

Views: 1812

Answers (2)

M Aur&#233;lio
M Aur&#233;lio

Reputation: 912

As I really appreciate the aesthetic appeal of this type of graph, especially when the information on the x-axis can be hidden, I found a somewhat laborious way to achieve it. I created intermediate levels for the color variables, defined a fixed size for each bar, and applied 100% transparency.

library(dplyr)
library(ggplot2)

dt_plot <-
  mpg %>% 
  count(class, drv)

# Empty_space is the size of the invisible bars
empty_space = max(dt_plot$n) * 0.02

# Create a dummy data.frame with the made up levels
empty_between <-
  distinct(dt_plot, class, drv) %>% 
  group_by(class) %>% 
  reframe(drv = runner::runner(drv, \(x) paste(x, collapse = "---"), k = 2, na_pad = TRUE )
  ) %>% 
  mutate(n = empty_space) %>% 
  filter(!is.na(drv))

# Add the dummy data to the original one
# You also have to define the colors explicit 
dt_plot %>%
  bind_rows(empty_between) %>% 
  ggplot(aes(class, n))+
  geom_col(aes(fill = drv, color = drv)) + 
  scale_fill_manual(values = setNames( scales::hue_pal()(3), c("4","f","r") ), na.value = "#FFFFFF00") +
  scale_color_manual(values = setNames( scales::hue_pal(l = 30)(3), c("4","f","r") ), na.value = "#FFFFFF00") + 
  theme(axis.ticks.y = element_blank(),
        axis.text.y = element_blank())

Created on 2024-03-04 with reprex v2.0.2

In addition to creating space between the boxes, you can also define the outline color.

Upvotes: 1

Axeman
Axeman

Reputation: 35342

Use a white border. Change the size to change the width of the gap. Note that the top and bottom of the bars no longer accurately reflect the true underlying values.

g + geom_bar(aes(fill = drv), color = 'white', size = 3) + theme_void()

enter image description here

Upvotes: 3

Related Questions