How to plot a graph of an integral using ggplot?

Viewed 25

I am trying to plot a graph of the following function:

enter image description here

My aim is that on the x-axis I have τ ranging from 0 to infinity and on the y-axis I have the result of the function, given that β and σ are known. I made the following R code:

NOTE: T is coded as Ti in the code to avoid mixing it up with T which stands for TRUE

fun_int <- function(Ti, tau){
  term_fun <- function(Ti, tau) {
    term <- (exp(-(log(Ti) - (beta - tau))^2/(2*(sigma^2))))/(sigma*sqrt(2*pi))
    return(term)
  } 
  int <- integrate(term_fun, 0, Inf)
  return(int)
}

beta <- 11.26
sigma <- 1.2

ggplot()+
  xlim(0, Inf)+
  geom_function(fun = fun_int)

However, it's not working:

Warning message:
Computation failed in `stat_function()`:
argument "tau" is missing, with no default 

I suspect that the problem may arise due to the fact that I'm not telling to the integrate function over which variable do I want to integrate, i.e. the part. With it not specified, it might as well be dT and the function wouldn't know. However, I don't know how to convey that information to the integrate function. I thought that it would perhaps help if I pass to ggplot which variable's values do I want to show on the x-axis, so I tried the following:

ggplot(mapping = aes(x = tau))+
  xlim(0, Inf)+
  geom_function(fun = fun_int)

However, this returns the following error:

Error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (1): x
---
Backtrace:
 1. base `<fn>`(x)
 2. ggplot2:::print.ggplot(x)
 4. ggplot2:::ggplot_build.ggplot(x)
 5. ggplot2 by_layer(function(l, d) l$compute_aesthetics(d, plot))
 6. ggplot2 f(l = layers[[i]], d = data[[i]])
 7. l$compute_aesthetics(d, plot)
 8. ggplot2 f(..., self = self)
 9. ggplot2:::check_aesthetics(evaled, n)

Another idea would perhaps be to pass some values to make a vector of τ. However, this is not what I want, since I want to graph the function without data and define what I want to see in the plot by setting the limits of the x axis with xlim, which should here range from 0 to infinity.

Even if I try to pass some sequence to tau:

 tau <- 1:5

I still get the same errors as before.

So then how can I plot this graph?

0 Answers
Related