2.6 Plotting a Function Curve

2.6.1 Problem

You want to plot a function curve.

2.6.2 Solution

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

Function curve with base graphics (left); With user-defined function (right)Function curve with base graphics (left); With user-defined function (right)

Figure 2.12: Function curve with base graphics (left); With user-defined function (right)

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:

With ggplot2, you can get a similar result (Figure 2.13), by using stat_function(geom = "line") and passing it a function that takes a numeric vector as input and returns a numeric vector:

A function curve with ggplot2

Figure 2.13: A function curve with ggplot2

2.6.3 See Also

See Recipe 13.2 for more in-depth information about plotting function curves.