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

Avi Gross @v|gro@@ @end|ng |rom ver|zon@net
Thu Mar 25 03:41:25 CET 2021

This may not be the right place to ask about ggplot which is part of
packages but are you aware how ggplot works additively?

You can say something like:

P <- ggplot(...) ... + ...

Then later say:

P <- p + geom_...()

And so on.

So if you set al the layers you want first into a variable like p, then in
an if statement you selectively add in one or another layer and finally add
in all remaining layers before printing it, would that simply meet your

Realistically, ggplot creates a data structure and the PLUS of other layers
updates or expands that structure but nothing happens till you print it and
it evaluates the data structure.

-----Original Message-----
From: R-help <r-help-bounces using r-project.org> On Behalf Of phil using philipsmith.ca
Sent: Wednesday, March 24, 2021 10:24 PM
To: r-help using r-project.org
Subject: [R] Including a ggplot call with a conditional geom in a function

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


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) {
     #if(posNeg({{MYy}})) geom_hline(yintercept=0,size=0.2)+   # This 
does not work
(plot1 <- plotLineFunc(df,a,b))
(plot2 <- plotLineFunc(df,a,c))

R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

More information about the R-help mailing list