0
votes

I wonder how I can get legend category for NA values in scale_fill_brewer. Here is my MWE.

set.seed(12345)
dat <- 
  data.frame(
    Row = rep(x = LETTERS[1:5], times = 10)
    , Col = rep(x = LETTERS[1:10], each = 5)
    , Y = c(rnorm(n = 48, mean = 500, sd = 1), NA, NA)
  )

dat$Y1 <-  addNA(cut(log(dat$Y), 5))

levels(dat$Y1)
[1] "(6.21,6.212]"  "(6.212,6.214]" "(6.214,6.216]" "(6.216,6.218]" "(6.218,6.22]"  NA   


library(ggplot2)

ggplot(data =  dat, aes(x = Row, y = Col)) + 
  geom_tile(aes(fill = Y1), colour = "white") +
  scale_fill_brewer(palette = "PRGn")

enter image description here

2
I think this is related to your question: github.com/hadley/ggplot2/issues/410mpalanco
Thanks a lot @aosmith for your helpful comment. Would you mind to change your comment to answer. ThanksMYaseen208

2 Answers

1
votes

You could explicitly treat the missing values as another level of your Y1 factor to get it on your legend.

After cutting the variable as before, you will want to add NA to the levels of the factor. Here I add it as the last level.

dat$Y1 <-  cut(log(dat$Y), 5)
levels(dat$Y1) <- c(levels(dat$Y1), "NA")

Then change all the missing values to the character string NA.

dat$Y1[is.na(dat$Y1)] <- "NA"

This makes NA part of the legend in your plot: enter image description here

1
votes

I've found a workaround without changing the original data frame, adding an extra legend based on this post:

ggplot(data =  dat, aes(x = Row, y = Col)) + 
   geom_tile(aes(fill = Y1), colour = "white") +
   scale_fill_brewer(palette = "PRGn")+
   geom_point(data = dat, aes(size="NA"), shape =NA, colour = "grey95")+
   guides(size=guide_legend("NA", override.aes=list(shape=15, size = 10)))

enter image description here

Colouring the NAs:

ggplot(data =  dat, aes(x = Row, y = Col)) + 
   geom_tile(aes(fill = Y1), colour = "white") +
   scale_fill_brewer(palette = "PRGn", na.value="red")+
   geom_point(data = dat, aes(size="NA"), shape =NA, colour = "red")+
   guides(size=guide_legend("NA", override.aes=list(shape=15, size = 10)))

enter image description here