Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine alpha and color in one legend

Tags:

r

ggplot2

I have a stacked bar graph where colors represent the category and I've adjusted the alpha to subdivide those into 2. The legend shows the alpha (in shades of grey) and the colors. However I would like to make a legend that contains the combinations.

To combine them I've looked at this question but I cannot combine the alpha and fill. Here is an reproducible figure that doesn't work:

mtcars %>% 
ggplot(aes(gear, mpg, fill = as.factor(vs), alpha = as.factor(am)))+
geom_bar(stat = "identity")+
scale_fill_manual(name = "legend",
                  values = c(
                      "0" = "red",
                      "1" = "blue",
                      "0"="red",
                      "1"="blue"
                      ),
                  labels = c("V-engine, automatic", 
                             "V-engine, manual",
                             "Straight-engine, automatic",
                             "Straight-engine, manual")
                  )+
scale_alpha_manual(name = "legend",
                   values = c(
                       "0" = 1,
                       "1"=2/5,
                       "0"=1,
                       "1"=2/5
                       ),
                   labels = c(
                       "V-engine, automatic", 
                       "V-engine, manual",
                       "Straight-engine, automatic",
                       "Straight-engine, manual"
                       )  )

image

like image 647
Roel Hogervorst Avatar asked Aug 31 '16 12:08

Roel Hogervorst


1 Answers

I approached your question not using aes(alpha) but treating alpha as fill.colour with combination of vs and am.

mtcars %>% 
  ggplot(aes(gear, mpg, fill = interaction(as.factor(vs), as.factor(am)))) +
    geom_bar(stat = "identity") +
    scale_fill_manual(name = "legend",
                      values = c(
                          "0.0" = alpha("red", 1),
                          "1.0" = alpha("blue", 1),
                          "0.1" = alpha("red", 2/5),
                          "1.1" = alpha("blue", 2/5)
                          ),
                      labels = c("V-engine, automatic", 
                                 "V-engine, manual",
                                 "Straight-engine, automatic",
                                 "Straight-engine, manual")
                      )

enter image description here

like image 118
cuttlefish44 Avatar answered Nov 13 '22 22:11

cuttlefish44