Search code examples
rggplot2probability-distribution

Simple way to plot a cumulative distribution function using TIdyverse?


I'm working through The R Book by Michael Crawley and I've arrived at a part where he is showing how to the behaviour of different probability functions. In this part he plots a simple cumulative distribution function:

curve(pnorm(x),-3,3)

Not a problem. But I wanted to do this using the tidyverse package. Reason being is that I've worked through two books that cover tidyverse and as I continue my education in R I might as well make it in sync with what I know up to this point. In all I've done I noticed I've never really learned how to plot the probability distributions. So using the knowledge I do have up to this point I attempted the following just as an exercise:

x = -8:8
norm_cum_table = data.frame(x,pnorm(x))
norm_plot = ggplot(data = norm_cum_table, mapping = aes(x = x)) + geom_line(mapping = aes(y = pnorm(x)))
norm_plot

And I successfully got a curve that "looks" like it might be the CDF, but it didn't look smooth enough for my liking.

Doing some fiddling and more reading I found another method to apply:

ggplot(data = norm_cum_table, mapping = aes(x = x)) + stat_function(fun = pnorm, args = list(sd=0.5))

This version looked a little smoother, but the issue for me is that I haven't really worked with the stat_function() up to this point. It hasn't been treated in any of the texts I've read.

I feel there must be an easier way to plot any of the probability distributions using Tidyverse in comparison to the amount of fiddling I had to do to get what should be a simple result.

I was wondering what other ways I could go about this?


Solution

  • Stealing from the ?stat_function help-file, which also has ?geom_function details, you could use:

    ggplot() + xlim(-5, 5) + geom_function(fun = pnorm)
    

    This should work with any function, user defined or already available.