0

I'm using nested ifelse statements to highlight extreme high/low values in a dataset. Rather than adding an extra column for colour aesthetics (I know how to do this), I wanted to try using aes_string(... , colour = ...) as this plot will go into a function (hence the aes_string instead of aes).

Below is a simple example of ggplot2 evaluating nested ifelse statements and incorrectly colouring incorrectly.

library(ggplot2)
theme_set(theme_bw())
sample <- data.frame(x = 1:10, y = 1:10)

# [Plot 1] Works fine using aes and stipulating variables
ggplot(sample, aes(x = x, y = y)) +
  geom_point(aes(colour = ifelse(x < 3, 1, ifelse(x > 7, 10, x)))) +
  scale_colour_identity()

# [Plot 2] "x" replaced by "var" and "aes" replaced by "aes_string"
var = "x"
ggplot(sample, aes(x = x, y = y)) +
  geom_point(aes_string(colour = ifelse(var < 3, 1, ifelse(var > 7, 10, var)))) +
  scale_colour_identity()

aes() works correctly

[Plot 1] You can see at the start and end the colours are highlighted blue (1) and red (10) respectively.

aes_string() doesn't work correctly

[Plot 2] You can see that all the points are highlighted red (10) indicating something has gone wrong.

Any help would be much appreciated!

Community
  • 1
  • 1
Alwin
  • 321
  • 2
  • 14
  • 2
    This is not a bug. for `aes_string` the parameter should be quoted explicitly. You can try: `var = "x"; aes_col <- gsub('var', var, 'ifelse(var < 3, 1, ifelse(var > 7, 10, var))'); ggplot(sample, aes(x = x, y = y)) + geom_point(aes_string(colour = aes_col)) + scale_colour_identity()`. – mt1022 Apr 08 '17 at 13:05
  • 2
    Or `aes_string(colour = "ifelse(get(var) < 3, 1, ifelse(get(var) > 7, 10, get(var)))")`. – lukeA Apr 08 '17 at 13:09
  • Ah, I see my mistake! An entire string needed to be passed to `colour`, not just the bits and piece I wanted. Thanks @mt1022, that works well. @lukeA, if you put your comment as an answer I'll happily accept it as the solution as it looks a tad more elegant to me – Alwin Apr 08 '17 at 13:15

0 Answers0