R: Custom equation on ggplot. stat_function with a third variable

Viewed 170

I am trying to introduce a custom equation to my ggplot.

data1989 %>% 
 ggplot(aes(x = daysAFTERFIRE, y = NDVI)) + 
 stat_function(fun= ~ (.meanNDVI)-(exp(-0.0000348*(.x)-2.17)))

As you see, my custom equation includes both y (column NDVI) and x (column daysAFTERFIRE), but also a third term, meanNDVI which is another column on my tibble.

Trying to run I get this:

Computation failed in `stat_function()`:
object '.meanNDVI' not found 

Anyone has any idea to solve this? Thanks!

1 Answers

You could build your function outside of the ggplot call, and then it might be easier to troubleshoot:

Assign your column containing a repeating mean value to a numeric variable:

meanNDVI_variable <- df$meanNDVI[1]

Then use it in your function:

f <- function(.x) (meanNDVI_variable)-(exp(-0.0000348*(.x)-2.17)))

Then:

data1989 %>% 
 ggplot(aes(x = daysAFTERFIRE, y = NDVI)) + 
 stat_function(fun= f)))
Related