Search code examples
rggplot2colorbrewer

R - why is my ColorBrewer palette wrong


I am doing a simple scatterplot in R and when I try to use the colorbrewer palette "RdBu" I am getting something clearly different and I have no idea why.

Here is a summary of my data

> summary(d$Year)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1880    1914    1947    1947    1980    2014 

> summary(d$NHem)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
-52.000 -21.500  -2.000   3.326  16.000  91.000 

> summary(d$NHem.bin)
-3 -2 -1  0  1  2  3  4  5 
 1 23 28 37 22  4  8 11  1 

when I use the command

ggplot(d, aes(x=Year, y=NHem, colour=NHem.bin)) + geom_point() + scale_fill_brewer(palette = "RdBu") 

i get this

enter image description here

So that's clearly not "RdBu". What am I doing wrong??

Also, I am creating a bin var so that I can try to maintain the same gradient across 3 separate plots.

Since I am already here, how do I reverse the scale so that the blue end corresponds to the more negative numbers and red corresponds to more positive?

thx


Solution

  • First, you got no fill aesthetics mapped. Second, you should either map a color aesthetic instead or specify a point shape that has a fill:

    library(ggplot2)
    ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +  
      geom_point() + 
      scale_color_brewer(palette = "RdBu") -> p1
    
    # or
    ggplot(mtcars, aes(wt, mpg, fill = factor(cyl))) +  
      geom_point(shape=21, color=NA) + 
      scale_fill_brewer(palette = "RdBu") -> p2
    
    gridExtra::grid.arrange(p1, p2)
    

    gives

    enter image description here