简体   繁体   中英

ggplot2: Legend for NA in scale_fill_brewer

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")

在此处输入图片说明

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: 在此处输入图片说明

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)))

在此处输入图片说明

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)))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM