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()
[Plot 1] You can see at the start and end the colours are highlighted blue (1) and red (10) respectively.
[Plot 2] You can see that all the points are highlighted red (10) indicating something has gone wrong.
Any help would be much appreciated!