Search code examples
rggplot2

behaviour of ecdf vs geom_function plot to box boundary


How can we control how far to the left and right end of the x-axis the functions in geom_function are plottet? My minimal example is an ecdf with overlay of geom_function. I use in geom="point" for clarity. Why does the red curve (geom_function) stop short of the edges/data?

ggplot()+stat_ecdf(aes(x=rnorm(100)),geom="point")+geom_function(fun=pnorm,color="red")

Using xlim outside does not seem to change behavior. By reducing the domain with xlim the red curve still stops short of the edges.


Solution

  • You can use coord_cartesian(expand = FALSE) to remove the expanded x axis:

    library(tidyverse)
    
    set.seed(1)
    
    xvals <- rnorm(100)
    
    ggplot() + 
      stat_ecdf(aes(x = xvals), geom = "point") + 
      geom_function(fun = pnorm, color = "red", xlim = range(xvals)) +
      coord_cartesian(expand = FALSE)
    

    enter image description here