首页 文章

模拟ggplot2默认调色板

提问于
浏览
146

我可以使用什么函数来模拟ggplot2的默认调色板以获得所需数量的颜色 . 例如,输入3将生成具有以下颜色的HEX颜色的字符向量:
enter image description here

4 回答

  • 51

    从15开始,色轮周围的色调相等!

    gg_color_hue <- function(n) {
      hues = seq(15, 375, length = n + 1)
      hcl(h = hues, l = 65, c = 100)[1:n]
    }
    

    例如:

    n = 4
    cols = gg_color_hue(n)
    
    dev.new(width = 4, height = 4)
    plot(1:n, pch = 16, cex = 2, col = cols)
    

    enter image description here

  • 82

    这是结果

    library(scales)
    show_col(hue_pal()(4))
    

    Four color ggplot

    show_col(hue_pal()(3))
    

    Three color ggplot

  • 198

    这些答案都非常好,但我想分享我在stackoverflow上发现的另一件事,这真的非常有用,这里是direct link

    基本上,@ DidzisElferts展示了如何获得ggplot用于构建您创建的绘图的所有颜色,坐标等 . 非常好!

    p <- ggplot(mpg,aes(x=class,fill=class)) + geom_bar()
    ggplot_build(p)$data
    [[1]]
         fill  y count x ndensity ncount  density PANEL group ymin ymax xmin xmax
    1 #F8766D  5     5 1        1      1 1.111111     1     1    0    5 0.55 1.45
    2 #C49A00 47    47 2        1      1 1.111111     1     2    0   47 1.55 2.45
    3 #53B400 41    41 3        1      1 1.111111     1     3    0   41 2.55 3.45
    4 #00C094 11    11 4        1      1 1.111111     1     4    0   11 3.55 4.45
    5 #00B6EB 33    33 5        1      1 1.111111     1     5    0   33 4.55 5.45
    6 #A58AFF 35    35 6        1      1 1.111111     1     6    0   35 5.55 6.45
    7 #FB61D7 62    62 7        1      1 1.111111     1     7    0   62 6.55 7.45
    
  • 41

    来自Hadley Wickham的ggplot2书的第106页:

    默认颜色方案scale_colour_hue在hcl色轮周围选择均匀间隔的色调 .

    通过一些逆向工程,您可以构建此函数:

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

    在条形图中证明这一点:

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

    enter image description here

相关问题