Lennon Lee
Lennon Lee

Reputation: 244

ifelse setting different argument in ggplot2

I have my dataframe:

test<-data.frame(F1=c(1,2,3,4,5),F2=c(3,4,5,6,7),Group=c("G1","G2","G2","G3","G1"))

I try to set up different point color at different condition:

FF<-function(Ture_or_not){
  p<-ggplot(test,aes(x=F1,y=F2))+
    geom_point(aes(color=Group),size=10)+
    scale_color_manual(values=ifelse(Ture_or_not==TRUE,c("yellow","red","black"),c("black","black","black")))
  p
}

FF(TRUE)

But I got:

Error: Insufficient values in manual scale. 3 needed but only 1 provided.
Run `rlang::last_error()` to see where the error occurred.

May I know what's the problem?

Upvotes: 1

Views: 1015

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389002

Agree with @Lefkios Paikousis' comment. Since you have a scalar input use a scalar function which is if/else instead of ifelse.

library(ggplot2)

FF<-function(True_or_not){
  ggplot(test,aes(x=F1,y=F2) )+
    geom_point(aes(color=Group),size=10)+
    scale_color_manual(values = if(True_or_not) c("yellow","red","black") 
                                else c("black","black","black"))
}

FF(TRUE)

Upvotes: 3

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521437

One solution here would be to just repeat the Ture_or_not value across the length of the color name vectors:

FF <- function(Ture_or_not) {
    p <- ggplot(test, aes(x=F1, y=F2)) +
        geom_point(aes(color=Group), size=10) +
        scale_color_manual(values=ifelse(rep(Ture_or_not, 3),
                          c("yellow","red","black"),
                          c("black","black","black"))
    )

    return(p)
}

FF(TRUE)

The idea here is that ifelse needs a boolean vector of the same length to decide which of the 3-vector values gets selected for each entry in those vectors. Your current version is passing in a scalar boolean value, which as a result is just returning a single entry (the first one actually) from either of the 3-vectors of colors.

Upvotes: 3

Related Questions