Search code examples
rplotfitdistrplus

plotting cumulative density plot using fitdistrplus object without a histogram


The R package fitdistrplus has a denscomp function that plots the fitted cumulative density curve along with a histogram of the data. As an R newbie, I appreciate all the plots available in this package.

Is there a simple way to just plot the curve without the histogram?

I couldn't find an option like histogram = FALSE in the denscomp function in the documentation.

How should I use the fitdist$estimate to plot just the cumulative density curve?


Solution

  • I'm not sure if there's an easy way to change the behavior of denscomp, but you can roll your own density plot using the distribution parameters returned by fitdist. Here's an example:

    Set up to plot three plots in a single window:

    par(mfrow=c(3,1), mar=c(4,4,3,1))
    library(fitdistrplus)
    

    Create a fitdist object using an example adpated from the help for denscomp:

    data(groundbeef)
    serving <- groundbeef$serving
    fitW <- fitdist(serving, "weibull")
    

    Now let's make a standard denscomp plot:

    denscomp(fitW, plotstyle="graphics", main="denscomp Version")
    

    Now we'll roll our own Weibull density using the parameters returned by fitdist. fitW$estimate contains the shape and scale parameters of the fitted Weibull distribution for the serving data. Below we generate the same plot as above using these parameters:

    x=seq(0, max(serving), length=100)
    serving_dwei = dweibull(x, shape=fitW$estimate["shape"], scale=fitW$estimate["scale"])
    
    hist(serving, freq=FALSE, main="Roll Your Own")
    lines(x=x, y=serving_dwei, col="red")
    

    And finally, the density plot alone:

    plot(x=x, y=serving_dwei, type="l", main="Density alone", xlab="Serving", ylab="Density")
    

    All three plots are shown below:

    enter image description here

    If you want to compare the Weibull fit with the empirical kernel density, you can do this:

    plot(x=x, y=serving_dwei, type="l", main="Weibull fit plus empirical density", 
         xlab="Serving", ylab="Density", 
         ylim=c(0,max(c(serving_dwei, density(serving)$y))))
    lines(density(serving), col="red")
    

    enter image description here