'Add white space between groups of multilevel stacked barplot ggplot

I have a multilevel dataset where I fill each box in a stacked bar with a particular colour, then add an outline box for another group that the variable belongs to. I am trying to find a way to separate white spaces between the secondary group (name in this example), rather than all boxes.

I have the code below:

set.seed(1)
a <- sample(30,20,T)
name <- sample(c('Bob','Alen'),20,T)
# class1 <- c(rep('a',100),rep('b',100))
thing <- sample(c('pen','box','phone'),20,T)
# class2 <- c(rep('pen',87),rep('box',113))
x <- rep(c(1,2,3,4),each=5)
plot_data <- cbind.data.frame(y=a,x=x,name=name,thing=thing)

plot_data$name <-
  factor(plot_data$name,
         levels = unique(plot_data$name))

plot_data$thing <-
  factor(plot_data$thing,
         levels = unique(plot_data$thing))


ggplot(data=plot_data,aes(fill=thing,x=x,y=y,group=name,colour=name)) + 
  geom_bar(position="stack", stat="identity",lwd=1.5)+
  scale_colour_manual(values = c("#a15c4e",1))+
  geom_label(aes(label=y),position = position_stack(vjust = 0.5),na.rm=T,label.size=1.2,show.legend=F)

Further, is it possible to fill the name boxes with white space rather than grey? I've found this difficult because the code tends to fill all boxes with white if I change fill.

Thanks in advance.



Solution 1:[1]

It's a bit of a hack, since there is no option to do this on a per-scale basis, but you could achieve it like this:

ggplot(data=plot_data,aes(fill=thing,x=x,y=y,group=name,colour=name)) + 
  geom_col(position = "stack", lwd = 1.5) +
  geom_col(position = "stack", lwd = 1.5, key_glyph = draw_key_point) +
  scale_colour_manual(values = c("#a15c4e", 1)) +
  geom_label(aes(label=y),position = position_stack(vjust = 0.5),
             na.rm=T,label.size=1.2,show.legend=F) +
  guides(color = guide_legend(override.aes = list(fill = "white", shape = 22,
                                                  cex = 7, linetype = 0),
                              keyheight = unit(20, "mm"))) +
  theme(legend.key = element_blank())

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Allan Cameron