2014-11-04 142 views
2

我已創建使用geom_smooth一個簡單的圖形:GGPLOT2:geom_smooth顏色與scale_colour_brewer

test.dat <- data.frame(matrix(c(runif(20, 0, 20)), 10, 2)) 
names(test.dat) <- c("x", "y") 

test.plot <- ggplot(test.dat, aes(x,y)) + geom_point() + 
        geom_smooth(method="loess") 

所產生是通過默認藍色的線。我可以通過添加此手動將其更改爲給定的顏色:

test.plot + geom_smooth(method="loess", colour="black") 

不過,我想基礎上,我已經使用了一系列情節的調色板上的顏色選擇。 (不使用scale_fill_brewer代替也不)

scale_colour_brewer(type = "div", palette = "Spectral") 

然而,這並沒有任何效果:通常,這將是通過將各行來實現的。我發現了一些顏色爲here的geom_smooth行爲的一些討論,但對於這個特定問題沒有明顯的解決方法。有什麼建議麼?

回答

3

您可以使用:

test.plot + 
    geom_smooth(aes(colour=TRUE), method="loess") + 
    scale_colour_brewer(type = "div", palette = "Spectral") 

的關鍵是使用colourmapping參數裏面geom_smooth(在aes部分)。使用什麼值並不重要,它必須與用於指定圖形中其他線條顏色的任何其他值不同。

這裏是一個更全面的例子:

set.seed(1) 
test.dat <- data.frame(
    x=runif(20), y=runif(20), 
    z=sample(letters[1:2], 20, rep=T) 
) 

ggplot(test.dat, aes(x, y, colour=z)) + 
    geom_smooth(aes(colour="d"), method="loess") + 
    geom_point() + 
    geom_line() + 
    scale_colour_brewer(type = "div", palette = "Spectral") 

enter image description here

注意我們是如何通過添加一個新的唯一值(「d」),以現有的顏色值,得到geom_smooth參加色階('a','b')。 Ggplot收集所有賦予colour唯美映射(在這種情況下爲unique(c(test.dat$z, "d")))的值,並將顏色從色標分配給它們。

+0

謝謝,那真是太棒了。如果沒有看到這種'顏色=真'的方式在之前把東西放進去;現在我明白了我是如何陷入困境的。再次感謝! – simoncolumbus 2014-11-05 13:55:41

+0

@simoncolumbus,如果這回答你的問題,請考慮檢查它的答案。 – BrodieG 2014-11-05 15:04:08