Search code examples
rggplot2geom-bar

format internal lines of a stacked geom_bar ggplot


I want to remove the internal borders from my ggplot, leaving a coloured border around the outside of each bar only. Here is a test data frame, with a stacked bar plot. Ideally, I will end up with the groups in the stack still being a shade of grey, with a colourful outline per box.

test <- data.frame(iso=rep(letters[1:5],3),
               num= sample(1:99, 15, replace=T),
               fish=rep(c("pelagic", "reef", "benthic"), each=5),
               colour=rep(rainbow(n=5),3))

ggplot(data=test, aes(x=iso, y=num, fill=fish, colour=colour)) +
  geom_bar(stat="identity") +
  theme_bw() + 
  scale_colour_identity() + scale_fill_grey(start = 0, end = .9)

enter image description here


Solution

  • You can accomplish this by moving the fill and colour aes() settings into two separate geom_bar() elements: one which takes the sum for each iso value (the outline), and another which splits things up by fish:

    ggplot(data=test, aes(x=iso, y=num)) +
      geom_bar(stat="summary", fun.y="sum", aes(color=colour)) +
      geom_bar(stat="identity", aes(fill=fish)) +
      theme_bw() + 
      scale_colour_identity() + 
      scale_fill_grey(start = 0, end = .9)
    

    enter image description here