2

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?

Tung
  • 26,371
  • 7
  • 91
  • 115
D.C. the III
  • 340
  • 3
  • 14
  • 3
    I know very little about *ggplot2*, but does `ggplot() + xlim(-5, 5) + geom_function(fun = pnorm)` do it? I stole that essentially from the help file in `?geom_function` - See under the `# To plot functions without data, specify range of x-axis` heading. – thelatemail Nov 27 '20 at 03:55
  • @thelatemail, sorry for the delay, but t=just tried it and it worked......awesome! Thanks for the help. Do you want to put it as answer so I can mark it is a correct? – D.C. the III Dec 04 '20 at 00:33
  • As requested, done! – thelatemail Dec 04 '20 at 00:36

1 Answers1

1

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.

thelatemail
  • 91,185
  • 12
  • 128
  • 188