Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 703
Brian19931 Avatar asked Sep 08 '25 16:09

Brian19931


2 Answers

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

like image 78
stefan Avatar answered Sep 10 '25 06:09

stefan


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"
like image 39
Maël Avatar answered Sep 10 '25 07:09

Maël