rggplot2colorsrgba

Get names of a color based on alpha value


Let say I supply R with a color name '#023e8a'

Now I want to get 5 following color names with alpha values as c(0.8, 0.6, 0.5, 0.3, 0.2), which will be passed to ggplot as fill aesthetics.

Is there any function available in R or ggplot to achieve this? I know that in ggplot I could pass alpha values in any layer, but I want to get specific names of the color shades.

Any pointer will be very appreciated.


Solution

  • One option to get the color "names" with alpha applied would be to use scales::alpha.

    library(ggplot2)
    library(scales)
    
    dat <- data.frame(
      x = LETTERS[1:5],
      y = 1:5
    )
    
    ggplot(dat, aes(x, y, fill = x)) +
      geom_col() +
      scale_fill_manual(values = scales::alpha('#023e8a', c(0.8, 0.6, 0.5, 0.3, 0.2)))
    

    If instead of adding transparency you just want different shades of a color then perhaps colorspace::lighten is more appropriate:

    ggplot(dat, aes(x, y, fill = x)) +
      geom_col() +
      scale_fill_manual(values = colorspace::lighten('#023e8a', 1 - c(0.8, 0.6, 0.5, 0.3, 0.2)))