# Plotting a ECDF in R and overlay CDF

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:

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?

• Maybe the red and black line overlay each other after 13?
– kristang
May 23, 2015 at 8:52
• 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. May 24, 2015 at 0:41

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.

    library(ggplot2)
set.seed(235)
x<-rgamma(40,2,scale=3)
p<-qplot(x,stat="ecdf",geom="step")+theme_bw()
p<-p+stat_function(fun=pgamma,color="blue",args=list(shape=2,scale=3))
p<-p+labs(title="ECDF and theoretical CDF")
p


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.

• +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. May 25, 2015 at 13:24