Ggplot2: Legend of NA at scale_fill_brewer

I wonder how I can get the category of legends for values NAin 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

0
source share
2 answers

You can clearly view the missing values ​​as another level of your factor Y1to get it in your legend.

After cutting the variable, as before, you need to add a NAfactor to the levels. 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 missing values ​​to a character string NA.

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

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

+1
source

, , :

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

NA:

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

+1

Source: https://habr.com/ru/post/1670404/


All Articles