6

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.table(yr=c(2010,2010,2011,2011),
                  val=c(1500,3000,2000,1100),
                  x=c("a","b","a","b"))


ggplot() + geom_bar(data=dt1, aes(x=yr, y=val,fill=x),stat="identity") +
  scale_x_continuous(breaks=dt1$yr)

This will create a simple chart with 2 columns with stacked data. I have tried the following code to adjust the 2011 value to have transparency, however I am not having much luck. Any pointers?

dt1[,alphayr:=ifelse(yr==2011,.5,1)]
ggplot() + geom_bar(data=dt1, aes(x=yr, y=val,fill=x),stat="identity", alpha=dt1$alphayr) +
scale_x_continuous(breaks=dt1$yr)
Dan
  • 2,625
  • 5
  • 27
  • 42
  • I think you want to put `alpha` in `aes`. `ggplot() + geom_bar(data=dt1, aes(x=yr, y=val,fill=x, alpha=alphayr),stat="identity")` – jazzurro Mar 11 '15 at 06:04
  • Thanks for the super fast response. I did try that, however I think the alpha values work differently in `aes`. Using a value of 0.5 makes it very faint, and a value of 0.9 isn't much better. Also within `aes` it adds another legend. – Dan Mar 11 '15 at 06:17

2 Answers2

11

First you put the alpha inside the aes as suggested by @jazzurro. However, you should use factor for this to get a discrete scale. Then you can manually adjust the alpha scale.

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')
shadow
  • 21,823
  • 4
  • 63
  • 77
3

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

lawyeR
  • 7,488
  • 5
  • 33
  • 63
  • adding the plot would've worked much better as an edit to shadow's answer (the data.frame part is completely pointless imo) – eddi Mar 11 '15 at 14:30
  • @eddi. Right. I did not think of editing someone else's answer to include the plot. As for the data frame part, not everyone uses data.table (I don't) and I thought what I did would help others like me. Anyway, thank you for taking the time to comment. – lawyeR Mar 11 '15 at 14:53