Reputation: 6345
I am trying to conditionally set an aes mapping based on a boolean. Here is what I am trying to do:
mydata <- data.frame(x=1:10,
y=runif(10),
categoryShort=LETTERS[1:2],
categoryLong=LETTERS[1:5])
mybool <- TRUE
myaes <- aes(x=x, y=y,
colour=ifelse(mybool, factor(categoryShort), factor(categoryLong)))
ggplot(mydata, myaes) + geom_point()
It ignores colour and screws up the whole legend.
I tried using aes_string, but it had the same problem:
aes_string(x="x", y="y",
colour=factor(ifelse(mybool, "categoryShort", "categoryLong")))
Upvotes: 2
Views: 1643
Reputation: 6345
It turns out aes_string CAN handle the factor function. So here's the solution:
colourMapping <- ifelse(mybool, "factor(categoryShort)", "factor(categoryLong)")
myaes <- aes_string(x="x", y="y", colour=colourMapping)
Upvotes: 4