Emulate ggplot2 default color palette

后端 未结 4 1479
猫巷女王i
猫巷女王i 2020-11-22 09:13

What function can I use to emulate ggplot2\'s default color palette for a desired number of colors. For example, an input of 3 would produce a character vector of HEX color

4条回答
  •  悲哀的现实
    2020-11-22 09:50

    From page 106 of the ggplot2 book by Hadley Wickham:

    The default colour scheme, scale_colour_hue picks evenly spaced hues around the hcl colour wheel.

    With a bit of reverse engineering you can construct this function:

    ggplotColours <- function(n = 6, h = c(0, 360) + 15){
      if ((diff(h) %% 360) < 1) h[2] <- h[2] - 360/n
      hcl(h = (seq(h[1], h[2], length = n)), c = 100, l = 65)
    }
    

    Demonstrating this in barplot:

    y <- 1:3
    barplot(y, col = ggplotColours(n = 3))
    

    enter image description here

提交回复
热议问题