[SOLVED] ggplot draw a black box without separation between bars

Issue

This Content is from Stack Overflow. Question asked by gaut

I have the following chart

year <- 2022:2026
data <- 15:11
data2 <- 10:6
data3 <- 1:5

dat <- tibble(year, data, data2, data3)
data <- dat %>% group_by(year) %>% pivot_longer(all_of(starts_with('data'))) %>% ungroup() %>%  
  mutate(first_categ = case_when('data2'==name | 'data3'==name ~ value,
                           TRUE ~ 0L))
ggplot(data, aes(x = year, fill = name))+
  geom_bar(aes(y = value), stat = 'identity', position = 'stack')+
  geom_col(aes(y=first_categ), alpha = 0, color = 'black', size = 2)

enter image description here

I’d like to have a separation between the two first colors (data2 and data3) and the rest because for me, these colors belong to the same category.

Is it possible to remove the intermediate horizontal separation between the blue and green?



Solution

This is trickier than you’d imagine. Effectively you need to map to different aesthetics and fake the guides to get this effect:

ggplot(data, aes(x = year)) +
  geom_col(aes(y = value, color = "data"), fill = "#F8766D", 
           position = 'stack') +
  geom_col(aes(y = value, fill = name), position = "stack", 
           data = subset(data, name != "data")) +
  stat_summary(fun = sum, aes(y = first_categ), color = 'black', 
           alpha = 0, size = 2, geom = "bar") +
  labs(color = "name") +
  scale_fill_manual(values = scales::hue_pal()(3)[-1], name = NULL) +
  guides(fill = guide_legend(override.aes = list(color = "black", size = 1.5),
                             byrow = TRUE),
         color = guide_legend(order = 1)) +
  theme(legend.margin = margin(20, 0, 20, 0),
        legend.key.size = unit(10, "mm"),
        legend.spacing.y = unit(-1.5, "mm"),
        legend.box.background = element_blank(),
        legend.background = element_blank(),
        legend.title = element_text(margin = margin(0, 0, 20, 0)))

enter image description here


This Question was asked in StackOverflow by gaut and Answered by Allan Cameron It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?