Search code examples
rggplot2geom-bar

transparent layers on a stacked bar plot using ggplot2


dt1 <- data.frame(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b"))
dt1$alphayr <- as.factor(ifelse(dt1$yr == "2011", 0.5, 1))

ggplot() + geom_bar(data=dt1, aes(x=yr, y=val, fill=x, alpha=factor(alphayr)), stat="identity") +
  scale_x_continuous(breaks=dt1$yr) +
  scale_alpha_manual(values = c("0.5"=0.2, "1"=1), guide='none')

enter image description here

Instead of controlling which whole bars are transparent, I need to control which layers are transparent.

How to make it so that all of the lowest layers are 100% transparent?


Solution

  • It looks like you can achieve what you want to do by setting alpha = 0 wherever x == "b":

    library(ggplot2)
    library(dplyr)
    
    dt1 <- tibble(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b")) %>% 
      mutate(alphayr = ifelse(x == "b", 0, 1))
    
    ggplot(dt1) + 
      geom_col(aes(x = yr, y = val, fill = x, alpha = alphayr)) +
      scale_alpha_identity()
    

    enter image description here