Home > other >  Get names of a color based on alpha value
Get names of a color based on alpha value

Time:10-24

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.

CodePudding user response:

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)))

CodePudding user response:

You can use scales::alpha:

library(scales)
alpha("#023e8a", c(0.8, 0.6, 0.5, 0.3, 0.2))
#[1] "#023E8ACC" "#023E8A99" "#023E8A80" "#023E8A4C" "#023E8A33"

CodePudding user response:

The other answers are good and I would use them.

However, if you are trying to reduce package dependencies, you can create a function that appends the hex value of each scaled alpha value to the color code:

append_alpha  <- function(color, alpha) {
    alpha_scaled  <- round(alpha*255)
    alpha_hex  <- as.hexmode(alpha_scaled)
    color_with_alpha  <- paste0(color, alpha_hex)

    return(color_with_alpha)
}

alpha_values  <- c(0.8, 0.6, 0.5, 0.3, 0.2)
append_alpha("#023e8a", alpha_values)
# "#023e8acc" "#023e8a99" "#023e8a80" "#023e8a4c" "#023e8a33"

If you are reducing dependencies because you are building code that other people will use, you will want to add some error handling for blank strings, invalid colors etc.

  • Related