if else condition in ggplot to add an extra layer
What you are seeing is a syntax error. The most robust way I can think of is:
tmp.data<-c(1,2,3)
if(tmp.data[1]!="no value") {
p = p + geom_point()
}
p + geom_line()
So you compose the object p
in a sequence, only adding geom_point()
when the if statements yields TRUE
.
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()