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

2. Quickly Exploring Data > Plotting a Function Curve

Plotting a Function Curve

Problem

You want to plot a function curve.

Solution

To plot a function curve, as in Figure 2-12, use curve() and pass it an expression with the variable x:

curve(x^3 - 5*x, from=-4, to=4)
Left: function curve with base graphics; right: with
            user-defined function
Figure 2-12. Left: function curve with base graphics; right: with user-defined function

You can plot any function that takes a numeric vector as input and returns a numeric vector, including functions that you define yourself. Using add=TRUE will add a curve to the previously created plot:

# Plot a user-defined function
myfun <- function(xvar) {
    1/(1 + exp(-xvar + 10))
}
curve(myfun(x), from=0, to=20)
# Add a line:
curve(1-myfun(x), add = TRUE, col = "red")

With the ggplot2 package, you can get a similar result using qplot() (Figure 2-13), by using stat="function" and geom="line" and passing it a function that takes a numeric vector as input and returns a numeric vector:


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

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

  

Start a Free 10-Day Trial


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