Search code examples
rggplot2plotlimitcurve

Why doesn't the function curves in R plot correctly when they exceed a functions boundry?


Let's say I have probability distribution function from some sort of function within a given boundry. Its total area is of course 1 within this boundry. It's defined as zero outside this boundry.

f <- function(z) 2*z^2 - 15*z + 15
fp <- function(x) f(x) * dunif(x, 10, 30) 
norm_const <- function(func, l=10, u=30) integrate(func, l, u)$value 
norm_pdf <- function(x) fp(x) / norm_const(fp)

Now if we use the curve function in R (or ggplot2's geom_function)

curve(norm_pdf, 0, 40)

enter image description here

As you can see the graphs curve does not go to zero directly at the lower and upper boundry for the value x. I want the plot to act the way like this code below (see red lines). However, I want when the curve hits zero, at both ends, to just become a straight line to infinity. Basically I want to graph to plot the curve as it should! There appears to be some kind of lagging effect on the curve for some reason? When it exceeds its boundry.

library(ggplot2)

ggplot() + geom_function(fun = norm_pdf) + xlab("x") + ylab("Density") + theme_minimal() + 
  scale_x_continuous(limits=c(0, 40), breaks=seq(0, 40,2)) + 
  geom_segment(aes(x = 10, y = 0, xend = 10, yend = norm_pdf(10)), color="red") +
  geom_segment(aes(x = 30, y = 0, xend = 30, yend = norm_pdf(30)), color="red") 

Solution

  • As Roland suggested, this solves it

    curve(norm_pdf, 0, 40, n = 1e6)
    

    and for the ggplot2 package the solution is

    stat_function(fun = norm_pdf, n=10^6)
    

    One can replace geom_function with stat_function and it works.