模拟ggplot2默认调色板

SFu*_*n28 170 r ggplot2

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

Joh*_*lby 239

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

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

例如:

n = 4
cols = gg_color_hue(n)

dev.new(width = 4, height = 4)
plot(1:n, pch = 16, cex = 2, col = cols)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 因为0 == 360 (17认同)
  • +1我喜欢您不错的,简单的解决方案,尽管我仍然试图理解为什么您在`seq`中有`length = n + 1'而我却有`length = n` (2认同)

Cli*_*der 111

这是结果

library(scales)
show_col(hue_pal()(4))
Run Code Online (Sandbox Code Playgroud)

四色ggplot

show_col(hue_pal()(3))
Run Code Online (Sandbox Code Playgroud)

三色ggplot

  • 为了便于复制和粘贴,十六进制值为:#f8766d - Red #00ba38 - Green #83b0fc - Blue (2认同)

Jos*_*rel 58

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

基本上,@ 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
Run Code Online (Sandbox Code Playgroud)


And*_*rie 43

来自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)
}
Run Code Online (Sandbox Code Playgroud)

在条形图中证明这一点:

y <- 1:3
barplot(y, col = ggplotColours(n = 3))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 您甚至可以使用`scales ::: show_col(ggplotColours(n = 3))`来显示颜色和值 (12认同)
  • 它甚至比这更简单.你可以避免使用第一行代数,虽然它不在帮助中,`hcl`回收值> 360. (2认同)