Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a color for NA data using ggplot2 and color brewer

I'm making a scatterplot of 2 continuous variables and a 4-level factor in R, using ggplot2. The 4-level factor column has some NAs in it.

p1 <- qplot(x_var, y_var, color=4_factor, data=df)
p1

...which works fine, colouring the NAs as grey and the factors using the default qualitative palette. But, my factors are ordered so I would prefer to use one of the diverging colour palettes from Color Brewer.

p2 <- p1 + scale_colour_brewer(palette="RdYlGn")
p2

Now, the NAs don't display as grey any more. How do I add an NA colour into the colour brewer palette please?

like image 828
user1684046 Avatar asked Apr 14 '16 15:04

user1684046


1 Answers

Add na.value to your call:

df =data.frame(x=rnorm(20), y=rnorm(20), 
  group=factor(sample(c(1:4,NA), size=10, replace=T)))
qplot(x, y, color=group, data=df) + 
  scale_colour_brewer(palette="RdYlGn", na.value="grey")
like image 82
fanli Avatar answered Sep 23 '22 13:09

fanli