# [R] Including a ggplot call with a conditional geom in a function

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Thu Mar 25 07:23:48 CET 2021

```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,

Às 02:24 de 25/03/21, phil using philipsmith.ca escreveu:
> How can I write an R function that contains a call to ggplot within it,
> with one of the ggplot geom statements being conditional? In my reprex,
> I want the plot to contain a horizontal zero line if the y values are
> both positive and negative, and to exclude the horizontal line if all of
> the y values are of the same sign. I tried a simple if statement, but it
> does not work. Suggestions appreciated. Philip
>
> library(rlang)
> library(tidyverse)
>
> a <- c(1:8)
> b <- c(23,34,45,43,32,45,68,78)
> c <- c(0.34,0.56,0.97,0.33,-0.23,-0.36,-0.11,0.17)
> df <- data.frame(a,b,c)
>
> posNeg <- function(x) {
>    ifelse(sum(x>0)>0 & sum(x>0)<length(x), y <- TRUE,y <- FALSE)
> }
> plotLineFunc <- function(MYdf,MYx,MYy) {
>      ggplot(MYdf,aes(x={{MYx}},y={{MYy}}))+
>      #if(posNeg({{MYy}})) geom_hline(yintercept=0,size=0.2)+   # This
> does not work
>      geom_line(colour="black",size=0.5)
> }
> (plot1 <- plotLineFunc(df,a,b))
> (plot2 <- plotLineFunc(df,a,c))
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

```