Search code examples
rcolorsggplot2colorbrewer

ggplot2: geom_smooth colour with scale_colour_brewer


I have created a simple graph using geom_smooth:

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")

The line that is produced is by default blue. I can change it manually to a given colour by adding this:

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

However, I would like to base the colour choice on a palette that I have been using for a series of plots. Normally, this would be achieved by adding the respective line:

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

Yet, this does not have any effect (nor does using scale_fill_brewer instead). I have found some discussion on the behaviour of geom_smooth with colour here, but no apparent fix for this particular problem. Any suggestions?


Solution

  • You can use:

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

    The key thing is to use colour inside the mapping argument to geom_smooth (the aes part). It doesn't matter what value you use, it just has to be distinct from whatever other values you're using to specify other line colors in the graph.

    Here is a fuller example:

    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

    Notice how we can get geom_smooth to participate in the colour scale by adding a new distinct value ('d') to the existing colour values ('a', 'b'). Ggplot collects all the values that are assigned to the colour aesthetic mapping (in this case, unique(c(test.dat$z, "d"))), and allocates colors from the color scale to them.