ggplot transparency on individual bar

后端 未结 2 759
被撕碎了的回忆
被撕碎了的回忆 2021-02-10 08:07

I am currently attempting to use ggplot to create a bar chart with a single bar that is partially transparent.

I have the following code:

dt1 <- data         


        
2条回答
  •  青春惊慌失措
    2021-02-10 09:03

    An instructive question and answer. Other readers may not use data.table syntax and may want to see the result, so I simply revised @shadow's answer to create a factor with a data frame, and display the plot below.

    dt1 <- data.frame(yr=c(2010,2010,2011,2011), val=c(1500,3000,2000,1100), x=c("a","b","a","b"))
    

    create the factor

    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.5, "1"=1), guide='none')
    

    enter image description here

提交回复
热议问题