rggplot2ecdfgeom-ribbon

How to define xaxis for a cumulative distribution function using ggplot and geom_ribbon in R?


I'm trying to produce a cumulative function using ggplot and stat_ecdf. Since I need the area under the curve to be colored, I'm using geom=="ribbon".

I need the x axis to be as highest as 20, however, I want to estimate the cumulative function until 100 (which is my highest variable value). For this, I'm using coord_cartesian.

This is the code I'm using:

Graph <- 
    ggplot(df, aes(x=var_x,fill=year)) +
    stat_ecdf(geom = "ribbon",alpha=0.5) +
    coord_cartesian(xlim = c(0, 20))+
    scale_y_continuous(breaks = seq(0, 1, 0.1),
                       labels = scales::percent, 
                       limits = c(0, 1),
                       expand = c(0,0))

However, I get the following error:

Error: geom_ribbon requires the following missing aesthetics: ymin and ymax or xmin and xmax

Does anyone know how to fix this? Any help is appreciated !!


Solution

  • I found a "manual" solution. First, I created a variable equal to the cumulative distribution of my variable of interest:

    df <- 
      df %>%
      dplyr::mutate(cumula_var = cume_dist(var_x))
    

    Then, I made the graph:

    Graph <- 
      ggplot(df, aes(x=var_x, y=cumula_var)) +
      geom_line() +
      geom_ribbon(aes(ymin = 0, ymax = ..y..,
                      xmin = 0, xmax = 20))+
      coord_cartesian(xlim = c(0, 20))