3

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))
Jamie
  • 401
  • 3
  • 11
  • 1
    Related - [How to use a variable to specify column name in ggplot](https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot) – Ronak Shah Jun 07 '21 at 03:15

1 Answers1

3

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

stefan
  • 90,330
  • 6
  • 25
  • 51
  • 1
    That's great, thanks for answering so quickly!! – Jamie Jun 06 '21 at 22:40
  • 1
    just to say thanks again - I implemented this in an app I'm making and it works perfectly! It means I can remove several huge if/else if statements and simply include a condition on what word gets put into the plot – Jamie Jun 07 '21 at 11:20
  • Hej Jamie. You are welcome. And thanks for saying thanks again. Always glad to help. And yes. Especially when working with shiny it's good to know the .data pro-noun. Best S. – stefan Jun 07 '21 at 11:48