2011-11-19 95 views
121

我可以使用什么函数来模拟ggplot2的默认调色板以获得所需数量的颜色。例如,为3的输入将产生的HEX颜色的字符向量与这些颜色: enter image description here仿真ggplot2默认调色板

+7

看鳞包 – hadley

+1

甜蜜! brewer_pal会非常有用 – SFun28

+1

是的!我在我的办公桌上保留了一个'display.brewer.all()'的打印输出。我认为我喜欢Set1是最好的因素。 –

回答

167

它仅仅是等距隔开的色调在色轮上,从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

+1

+1我喜欢你的漂亮,简单的解决方案,尽管我仍然试图理解'seq'中为什么有'length = n + 1',而我有'length = n' – Andrie

+9

因为0 == 360 – hadley

35

从哈德利韦翰的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) 
} 

在barplot演示这一点:

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

enter image description here

+2

它比这更简单。你可以避免代数的第一行,因为虽然它不在帮助中,但是“hcl”可以循环使用大于360的值。 –

+10

甚至可以使用'scales ::: show_col(ggplotColours(n = 3))'来显示颜色和值 –

41

这些答案都很好,但我想分享另一件我在stackoverflow上发现的东西,这真的很有用,这里是t他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 
52

这是

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

Four color ggplot

show_col(hue_pal()(3)) 
结果

Three color ggplot

+1

奇怪的是,颜色(至少在第二张图片中)与RGB代码不匹配。但是,看一下我在本地制作的图形,这些RGB代码*是正确的。 – Sparhawk

+1

也许是它的浏览器的东西? –

+1

是的,很奇怪。在Firefox中,绿色是#15ba3e,在Chromium中是绿色#00b83a,并且在下载图像并在专用图像程序(Gwenview)中观看后,它是#00b839。只有Konqueror正确显示为#00ba38。所以只有一个是对的,没有一个是一致的! – Sparhawk

相关问题