2011-11-19 83 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

相關問題