2013-08-23 97 views
0

我試圖生產使用GGPLOT2庫漸進圖中R.選擇色相/啤酒顏色GGPLOT2

我的意思「進步」的是,對於演示的目的,我想行添加到每次繪製一個,所以我生成了多行多行的單個繪圖,每個繪製一條線。

在ggplot2中,例如使用scale_colour_hue()可以很好地工作,除了每條線的顏色從圖轉換爲圖。我想保持顏色不變(即圖1的第1行有X顏色,圖5的第1行仍然有X顏色等)。我可以通過使用scale_colour_manual()手動聲明顏色來實現這一點,但我覺得受到這些顏色美學的限制(「紅色」,「藍色」等)。我是否真的必須爲每種顏色找出十六進制值,例如在色相調色板中,還是有更簡單的方法,我可以指示scale_colour_hue()函數在每次添加新行時以固定順序使用其調色板?

謝謝,感謝幫助!

+0

在開始之前,你知道所需的總行數嗎? – mnel

回答

3

如果你事先知道你要添加的行總數,你可以創建一個合適的顏色和名稱使用的規模與scale_colour_manual

library(RColorBrewer) 
library(plyr) 
# a function to create a brewer palette of any length (kittens will be killed) 
myBrewerPal <- function(pal = 'Spectral'){ 
    colorRampPalette(brewer.pal(name = pal, n = 11)) 
} 

# function to create a named vector of colours for a given 
# vector x 
create.palette <- function(x, pal = 'Spectral'){ 
    ux <- sort(unique(x)) 
    n <- length(ux) 
    setNames(myBrewerPal(pal)(n), ux) 

} 

# create a manual scale with the named values part 
myPal <- scale_colour_manual(name = 'Gear', values = create.palette(factor(mtcars$gear))) 


# the base plot (no lines) 
baseplot <- ggplot(mtcars, aes(x=hp, y = disp, colour = factor(gear))) + myPal 
# 1 line 
baseplot + geom_line(subset = .(gear==3)) 

enter image description here

# 2 lines (gear = 3 is consistent) 
baseplot + geom_line(subset = .(gear %in% 3:4)) 

enter image description here