Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

13. Miscellaneous Graphs > Plotting a Function

Plotting a Function

Problem

You want to plot a function.

Solution

Use stat_function(). It’s also necessary to give ggplot() a dummy data frame so that it will get the proper x range. In this example we’ll use dnorm(), which gives the density of the normal distribution (Figure 13-4, left):

# The data frame is only used for setting the range
p <- ggplot(data.frame(x=c(-3,3)), aes(x=x))

p + stat_function(fun = dnorm)
Left: The normal distribution. Right: The
            t-distribution with df=2
Figure 13-4. Left: the normal distribution; right: the t-distribution with df=2

Discussion

Some functions take additional arguments. For example, dt(), the function for the density of the t-distribution, takes a parameter for degrees of freedom (Figure 13-4, right). These additional arguments can be passed to the function by putting them in a list and giving the list to args:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint