Make ggplot aes color mapping conditional on logical statement

Viewed 274

I would like to make the color mapping in a ggplot conditional on the results of a logical test. So for example, I can give an input, and then set the color aes to either a, b, or c. However, I can't seem to get it to work, as the only way I can manage to do it is by passing in something like "a", which of course then does not actually map to column a from the data. Any help would be much appreciated!

test.data <- tibble(nums = seq(1:6),
                    a = c("a","a","a", "b", "b", "b"),
                    b = c("a","a", "b", "b", "a","a"),
                    c = c("a", "b", "a", "b", "a", "b"))

ggplot(data = data) +
  geom_point(aes(x = nums, y = nums, color = a))

color.choice <- "a"

ggplot(data = data) +
  geom_point(aes(x = nums, y = nums, color = color.choice))
1 Answers

This could be achieved via e.g. the .data pro-noun which allows you to select columns passed as a character string:

library(ggplot2)

test.data <- data.frame(nums = seq(1:6),
                    a = c("a","a","a", "b", "b", "b"),
                    b = c("a","a", "b", "b", "a","a"),
                    c = c("a", "b", "a", "b", "a", "b"))

color.choice <- "a"

ggplot(data = test.data) +
  geom_point(aes(x = nums, y = nums, color = .data[[color.choice]]))

Related