Add a second legend for NA values in scale_colour_gradient() or scale_fill_brewer() etc?

32 views
Skip to first unread message

Kenny Bell

unread,
Oct 2, 2014, 2:35:44 AM10/2/14
to ggp...@googlegroups.com
For example,

miss <- sample(c(NA, 1:5), nrow(mtcars), rep = TRUE) qplot(mpg, wt, data = mtcars, colour = miss)


How would one get a second legend object showing the missing values are gray?

Dennis Murphy

unread,
Oct 2, 2014, 11:53:27 AM10/2/14
to Kenny Bell, ggplot2
Hi:

If you want NA represented in the legend, you can finagle the NA in
miss to become an actual factor level and then set the desired color
for it. Here's the basic idea:

library(ggplot2)

miss1 <- miss # Copy original vector
# Coerce missing values to be character (=> miss1 is coerced to character)
miss1[is.na(miss1)] <- as.character("NA")
miss1 <- factor(miss1) # NA is now a factor level

qplot(mpg, wt, data = mtcars, colour = miss1) +
scale_colour_manual(values = c(rainbow(5), "grey40")) +
labs(colour = "Value")

The choice of rainbow(5) for the first five levels is not an inspired
choice, but it illustrates the idea. There are any number of color or
palette choices from which you can choose.

FYI, in ggplot2 there is exactly one mapping to any single aesthetic.
More specifically, you cannot generate two legends or colorbars for
the same aesthetic.

Dennis
> --
> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> Please provide a reproducible example:
> https://github.com/hadley/devtools/wiki/Reproducibility
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>
> ---
> You received this message because you are subscribed to the Google Groups
> "ggplot2" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to ggplot2+u...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages