Skip to content
Prev 387591 / 398502 Next

Including a ggplot call with a conditional geom in a function

Hello,

In the following code, the fixed parts of the plot are drawn first, 
assigning the plot to p. Then geom_hline is conditionally added to p and 
the result returned to caller.
This may be a problem if the conditional geom needs to be in a specified 
order in the plot. Function plotLineFunc2 adds everything in the order 
of the question and is probably a better way of solving the problem.

I have also rewritten posNeg() without ifelse.

posNeg <- function(x) sum(x>0)>0 & sum(x>0)<length(x)

plotLineFunc <- function(MYdf,MYx,MYy) {
   p <- ggplot(MYdf,aes(x={{MYx}},y={{MYy}}))+
     geom_line(colour="black",size=0.5)
   if(posNeg({{MYy}}))
     p + geom_hline(yintercept=0,size=0.2)
   else p
}

plotLineFunc2 <- function(MYdf,MYx,MYy) {
   p <- ggplot(MYdf,aes(x={{MYx}},y={{MYy}}))
   p <- if(posNeg({{MYy}}))
     p + geom_hline(yintercept=0,size=0.2)
   else p
   p + geom_line(colour="black",size=0.5)
}


(plot1 <- plotLineFunc(df,a,b))
(plot2 <- plotLineFunc(df,a,c))


Hope this helps,

Rui Barradas

?s 02:24 de 25/03/21, phil at philipsmith.ca escreveu: