R ggplot transparency - alpha values conditional on other variable

后端 未结 2 545
攒了一身酷
攒了一身酷 2021-02-18 22:39

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          


        
相关标签:
2条回答
  • 2021-02-18 23:25

    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

    0 讨论(0)
  • 2021-02-18 23:39

    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

    0 讨论(0)
提交回复
热议问题