Skip to content

Instantly share code, notes, and snippets.

@seananderson
Last active February 8, 2018 19:49
Show Gist options
  • Save seananderson/5b64f65f9edd9376c7acd5f4ae2ce6c7 to your computer and use it in GitHub Desktop.
Save seananderson/5b64f65f9edd9376c7acd5f4ae2ce6c7 to your computer and use it in GitHub Desktop.
library(tidyverse)
d <- tibble(group = letters[1:5], x = 1:5, y = rnorm(5))
ggplot(d, aes(x, y, colour = group)) + geom_point(size = 3)
# lose group
d <- d[-2,]
ggplot(d, aes(x, y, colour = group)) + geom_point(size = 3)
# fix by joining in all known groups to create NAs:
all_groups <- tibble(group = letters[1:5])
d <- full_join(d, all_groups) # <- key part here
d
ggplot(d, aes(x, y, colour = group)) + geom_point(size = 3)
# or more elegantly, define the factor levels and use drop = FALSE:
d <- d[-2,] # lose group
d$group <- factor(d$group, levels = c("a", "b", "c", "d", "e"))
ggplot(d, aes(x, y, colour = group)) + geom_point(size = 3) +
scale_color_discrete(drop = FALSE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment