I need to plot a ECDF in R and overlay a CDF. In my case I have to do this with the gamma distribution where alpha = 2, beta = 3, and for example, with a sample size of 40, so it is pretty straightforward.

plot(ecdf(rgamma(40, 2, 1/3)))
lines(x, pgamma(x, shape = 2, scale = 3), type="l", col = "red")

I'm not sure, but I think that the above should be correct (I read somewhere that rgamma use lambda as parameter, so that's why it's 1/3 and scale refers to beta according to what I read, so it's just 3).

The result is the following plot:

enter image description here

I wonder if what I did is okay, if it is... then the only thing I don't understand is, why does the red line reaches until x has a value of 12 or 13?

  • $\begingroup$ Maybe the red and black line overlay each other after 13? $\endgroup$
    – kristang
    May 23, 2015 at 8:52
  • $\begingroup$ You don't say what's in x (give minimum reproducible example, please), but I bet max(x) is right where the red line stops. It did what you told it to do ... if you want it to draw higher, give it higher values to draw. $\endgroup$
    – Glen_b
    May 24, 2015 at 0:41

1 Answer 1


Yes, what you have done is ok. You were right to worry about the default parameters of the Gamma distribution, because if you do not specify the scale, then R defaults to rate which is 1/scale.

When it comes to the graph though, might I suggest though an upgrade to ggplot2? The picture becomes much clearer this way.

    p<-p+labs(title="ECDF and theoretical CDF")

enter image description here

As you can see the two curves are reasonably close, even with 40 samples. And they are more discernible as well. If you like then, there are many tutorials on ggplot2 out there that you can follow.

  • $\begingroup$ +1 - the reason the base plot is hard to read though is because of the extreme aspect ratio - which has nothing directly to do with using ggplot or base graphics. $\endgroup$
    – Andy W
    May 25, 2015 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.