Loading...

Generating a boxplot with slightly darker lines then the fill color


To generate less distracting boxplots it would be nice to have a similar color scale for fill and color. How can I achieve this without guesswork?

- - Source

Answers

answered 1 week ago jakob-r #1

Predefined colors (scale_*_manual)

Simple solution using colorspace::darken()

This is the easiest solution I guess:

library(ggplot2)
library(colorspace)

hex_colors = c(
  setosa = "#80adf7", 
  versicolor = "#96ef8f", 
  virginica = "#f4a1df")

g = ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species, color = Species))
g + geom_boxplot() + 
  scale_fill_manual(values = hex_colors) + 
  scale_color_manual(values = darken(hex_colors, amount = 0.3))

Manually calculating the colors

If you want to have more control, you can convert the HEX to RGB and decrease all values of red, green and blue a bit. You could also convert it to HSV and play easier with hue, saturation, and the luminosity value by adding rgb2hsv to the pipelne and calling hsv instead of rgbat the end.

library(ggplot2)
library(magrittr)
library(purrr)

hex_colors = c(
  setosa = "#80adf7", 
  versicolor = "#96ef8f", 
  virginica = "#f4a1df")

dark_colors = hex_colors %>% 
  col2rgb %>% #convert HEX colors to RGB Matrix
  "*"(0.7) %>% # make each component "darker"
  apply(2, lift_dv(rgb, maxColorValue = 255)) # Convert each column to HEX again

g = ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species, color = Species))
g + geom_boxplot() + 
  scale_fill_manual(values = hex_colors) + 
  scale_color_manual(values = dark_colors)

Both approaches lead to the following result:

Boxplots

Automatic colors (scale_*_discrete)

scale_*_discrete works with the HSL color space. We can just define the luminance manually.

library(ggplot2)
g = ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species, color = Species))
g + geom_boxplot() + 
  scale_fill_discrete(l = 70) + # a bit brighter
  scale_color_discrete(l = 50) # a bit darker

boxplot 2

answered 1 week ago PoGibas #2

Another solution is simply to pass alpha() to scale_FOO_manual. With it we only need to specify wanted alpha and color values:

library(ggplot2)

color <- c("red", "blue", "green")
alpha_color <- 1
alpha_fill <- 0.2

ggplot(iris, aes(Species, Sepal.Length, fill = Species, color = Species)) +
  geom_boxplot() + 
  scale_fill_manual(values = alpha(color, alpha_fill)) + 
  scale_color_manual(values = alpha(color, alpha_color))

enter image description here

comments powered by Disqus