Add a color for NA data using ggplot2 and color brewer
Asked Answered
E

1

6

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?

Emlen answered 14/4, 2016 at 15:7 Comment(0)
A
8

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")
Aalesund answered 14/4, 2016 at 15:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.