sharoz
sharoz

Reputation: 6345

Conditionally set an aes mapping for ggplot2

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

Answers (1)

sharoz
sharoz

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

Related Questions