Home > database >  Adding independent fill and alpha aesthetics with `geom_histogram()`
Adding independent fill and alpha aesthetics with `geom_histogram()`

Time:08-29

I sometimes think it's useful to have an alpha dimension as well as a color/fill dimension in a plot. In ggplot2, it's pretty natural to do this with geom_point, but I'm struggling to map the alpha aesthetic using geom_histogram. Is it possible to create a histogram where parts of each bar are colored (with fill aesthetic) according to one variable, and made transparent (perhaps with an alpha aesthetic) according to a different one?

library(tidyverse)

# different color and alpha can be done easily with geom_point
mtcars %>% 
  ggplot(aes(x = wt, y = mpg, color = as.factor(gear), alpha = cyl))  
  geom_point()


# not happening with geom_histogram
mtcars %>% 
  ggplot(aes(x = wt, fill = as.factor(gear), alpha = cyl))  
  geom_histogram()

Thanks!!

EDIT This seems like a step in the right direction:

mtcars %>% 
  mutate(cyl_gear = paste(cyl, gear, sep = "_")) %>% 
  ggplot(aes(x = wt, fill = cyl_gear, color = as.factor(cyl)))  
  scale_fill_manual(values = 
                      sort(unlist(map(1:n_distinct(mtcars$gear)
                                 , function(ge){hcl.colors(n_distinct(mtcars$cyl), alpha = ge/n_distinct(mtcars$gear))}))))  
  scale_color_manual(values = sort(hcl.colors(n_distinct(mtcars$cyl))))  
  geom_histogram()

To be complete, I would accommodate arbitrary numeric alpha values given by the data.

CodePudding user response:

It is possible to do this by assigning one variable to fill, one variable to alpha, and a grouping variable comprising the interaction of the two. In this grouping, the alpha variable should be listed first so that colors group together within bars.

mtcars %>% 
  ggplot(aes(x = wt, fill = factor(gear), alpha = cyl, 
             group = interaction(cyl, gear)))  
  geom_histogram() 

enter image description here

  • Related