if else condition in ggplot to add an extra layer

前端 未结 4 570

say I want to plot two layers in ggplot, one containing points and another one containing lines if a certain criteria is fulfilled.

The code without the criteria cou

4条回答
  •  暖寄归人
    2020-11-30 09:15

    This was done using ggplot2 2.1.0. I think you can do exactly what the OP wished, just by switching the parenthesis so that they encompass the entire if statement.

    Here is an example that add a horizontal line depending on if Swtich is T or F. First, where the condition is TRUE

    library(ggplot2)
    
    df<-data.frame(x=1:10,y=11:20)
    Switch=T
    
    ggplot(df,aes(x,y))+
    {if(Switch)geom_hline(yintercept=15)}+
      geom_point()
    

    Now, the same thing but the condition is FALSE

    df<-data.frame(x=1:10,y=11:20)
    Switch=F
    
    ggplot(df,aes(x,y))+
    {if(Switch)geom_hline(yintercept=15)}+
      geom_point()
    

提交回复
热议问题