2014-11-04 143 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