Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ggplot transparency - alpha values conditional on other variable

I have the following data: [example from R graphics Cookbook]

Cultivar Date Weight sd          n  se          big
c39     d16   3.18  0.9566144   10  0.30250803  TRUE
c39     d20   2.8   0.2788867   10  0.08819171  TRUE
c39     d21   2.74  0.9834181   10  0.3109841   TRUE
c52     d16   2.26  0.4452215   10  0.14079141  FALSE
c52     d20   3.11  0.7908505   10  0.25008887  TRUE
c52     d21   1.47  0.2110819   10  0.06674995  FALSE

I would like to have a bar plot where bar transparency depends on big variable.

I have tried the following, where I tried to set alpha values depending on different big values:

ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
  geom_bar(position="dodge", stat="identity")
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
  geom_bar(position="dodge", stat="identity", alpha=cabbage_exp$big=c("TRUE"= 0.9, "FALSE" = 0.35)) 
ggplot(cabbage_exp, aes(x=Date, y=Weight, fill=Cultivar)) +
 geom_bar(position="dodge", stat="identity", alpha=big=c("TRUE"= 0.9, "FALSE" = 0.35))

I would like to have different transparency in the bars depending on the value of the big variable. Any help or guidance hugely appreciated!

like image 701
user3507584 Avatar asked Jul 17 '14 10:07

user3507584


2 Answers

Another possibility using scale_alpha_discrete, where the range argument may be used to set your desired alpha values for each level of 'big'.

ggplot(data = cabbage_exp, aes(x = Date, y = Weight, fill = Cultivar, alpha = big)) +
  geom_bar(position = "dodge", stat = "identity") +
  scale_alpha_discrete(range = c(0.35, 0.9))

enter image description here

like image 55
Henrik Avatar answered Oct 30 '22 12:10

Henrik


The problem here is that your variable is discrete, whereas the alpha scale is continuous. One way to do it is to manually compute your alpha values before plotting :

alpha <- ifelse(d$big, 0.9, 0.35)
ggplot(d, aes(x=Date, y=Weight, fill=Cultivar)) +
    geom_bar(position="dodge", stat="identity", aes(alpha=alpha))

The downside is that you won't get a correct legend for your alpha values. You can delete it with this :

ggplot(d, aes(x=Date, y=Weight, fill=Cultivar)) +
    geom_bar(position="dodge", stat="identity", aes(alpha=big)) +
    scale_alpha_continuous(guide=FALSE)

Final result :

enter image description here

like image 39
juba Avatar answered Oct 30 '22 11:10

juba