Skip to main content
v2026.11,986 entries · CC-BY 4.0

Plot a Function in R: curve() and ggplot2 geom_function()

Plot a function in R with base curve() or ggplot2 geom_function(): ranges, vectorised functions, overlays and fixes for the common errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

To plot a function in R, pass it to curve() in base R, for example curve(sin, -2*pi, 2*pi), or add geom_function(fun = ...) to a ggplot2 plot with the x-range set by xlim(). Both evaluate your function at a grid of equally spaced x values (101 by default) and join the points with a line, so the function must accept a vector and return a vector of the same length.

What it is used for in research

Researchers plot a function when the object of interest is a formula rather than a table of observations: a theoretical probability density next to a histogram, a dose-response model, a calibration curve, a decay law or a prior distribution in a Bayesian analysis. Drawing the curve lets you check the shape of a model before fitting it, add a reference line to observed data, or produce a figure for a methods section. If your data are measured points rather than a formula, see our guide to the plotnine grammar-of-graphics library or the guide to importing a dataset in RStudio instead.

Plotting functions in R, plot functions in R and function plot in R

These phrasings all describe the same task and the same two tools. Base R ships with curve() in the graphics package. The ggplot2 package provides geom_function() and its underlying statistic stat_function(). Everything below applies to a single function or to several functions on the same axes.

How to install or access it

curve() is part of the graphics package that is loaded in a standard R session, so nothing extra is needed. R itself is distributed through CRAN, the Comprehensive R Archive Network; the Windows download page at cran.r-project.org/bin/windows/base lists R 4.6.2 as the current release as of 2026-11-14, and the same site carries the macOS and Linux builds. For ggplot2, install the package once and load it in each session:

install.packages("ggplot2")library(ggplot2)

The ggplot2 reference for geom_function() is published at ggplot2.tidyverse.org/reference/geom_function.html, and the reference for curve() is in the R documentation for the graphics package (stat.ethz.ch/R-manual/R-devel/library/graphics/html/curve.html). Both were checked on 2026-11-14.

Step-by-step: plot a function in R

Option 1: base R with curve()

The documented usage is curve(expr, from = NULL, to = NULL, n = 101, add = FALSE, type = "l", xname = "x", xlab = xname, ylab = NULL, log = NULL, xlim = NULL, ...). The steps are:

  1. Choose the function. expr is either the name of a function or a call or expression written in terms of a variable called x. A bare function name is called with one argument.
  2. Set the range. Give from and to. If you leave them out when starting a new plot, the range defaults to 0 to 1, which surprises many users who expect a wider window.
  3. Run the call. The documentation’s own example is a sine wave over two periods with the variable renamed to t:
    curve(sin, -2*pi, 2*pi, xname = "t")
  4. Use an expression when you need a formula. Write it in terms of x (or whatever you set xname to):
    curve(x^2, from = -3, to = 3)
  5. Overlay a second curve. Call curve() again with add = TRUE; the new curve is drawn on the existing plot and takes its x-limits from the previous plot when from and to are omitted.
    curve(dnorm, -4, 4)curve(dt(x, df = 1), add = TRUE)

Option 2: ggplot2 with geom_function()

  1. Create an empty plot with an x-range. A function layer has no data of its own, so the range comes from the scale:
    base = ggplot() + xlim(-5, 5)
  2. Add the function layer. Pass a function name, an anonymous function or a formula to fun:
    base + geom_function(fun = dnorm)
  3. Pass extra arguments with args. Parameters for the function go in a list rather than inside the call:
    base + geom_function(fun = dnorm, args = list(mean = 2, sd = .5))
  4. Write an anonymous function. The ggplot2 reference shows both the backslash form and the formula form:
    base + geom_function(fun = (x) 0.5 * exp(-abs(x)))base + geom_function(fun = ~ 0.5 * exp(-abs(.x)))
  5. Plot several functions with a legend. Map a label to colour inside aes():
    base +  geom_function(aes(colour = "normal"), fun = dnorm) +  geom_function(aes(colour = "t, df = 1"), fun = dt, args = list(df = 1))
  6. Overlay a theoretical curve on observed data. The reference example draws a normal density over a kernel density estimate of simulated values:
    ggplot(data.frame(x = rnorm(100)), aes(x)) +  geom_density() +  geom_function(fun = dnorm, colour = "red")

    To summarise the observed data you are comparing against, our guide to the psych package in R covers descriptive statistics.

Plot a function in R programming: how the two approaches map to each other

The data table below sets the arguments of curve() beside those of geom_function() and stat_function(), taken from the two reference pages. The same idea has a different name in each system, which is the usual source of confusion when moving between them.

Output and how to read it

Each call draws a line through the evaluated points. With curve() the default is 101 points; with ggplot2’s n the default is also 101. A smooth function such as sin or dnorm looks continuous at that resolution. The curve is a set of straight segments between the evaluated points, so a feature narrower than the grid spacing can be missed.

The R documentation for curve() warns that it gives poor results for non-smooth functions. If your function has a jump, a kink or a sharp spike, increase n and compare the picture at two values of n before trusting it.

Reusing the computed values

curve() returns, invisibly, a list with components x and y. Assign the call to a variable to keep the values you plotted:

res = curve(sin, -2*pi, 2*pi)head(res$x)head(res$y)

In ggplot2, the layer computes x and y through the statistic, available as after_stat(x) and after_stat(y) when you need to map them to another aesthetic.

Log scales

In curve(), the log argument puts the x axis, the y axis or both on a log scale, and the evaluation points are then equally spaced on the log scale rather than on the raw x scale. See our guide to a logarithmic plot in MATLAB if you work in both environments and want the equivalent idea there.

Troubleshooting

The function does not accept a vector

Both reference pages require the function to be vectorised: given a vector of n x values it must return n values. A function that uses if on a whole vector, or that returns a single summary number, will fail. Rewrite it with ifelse() or wrap it with Vectorize(). The curve() documentation states that a function that does not return a vector of the right length raises an error.

The plot shows only 0 to 1

When you start a new plot with curve() and give no from or to, the range defaults to (0, 1). Supply the range explicitly. When add = TRUE (or NA), the range is taken from the previous plot instead, a behaviour changed in R 2.14.0.

The ggplot2 plot is empty or has the wrong range

Without data, ggplot2 needs a range. Add xlim() to the plot, or pass xlim inside geom_function(). In the reference examples, xlim = c(-1, 1) restricts the curve and c(-7, 7) widens it.

The curve looks jagged

Raise n. Evaluating at too few points joins sparse points with straight lines; the ggplot2 reference demonstrates this on purpose with stat_function(fun = dnorm, geom = "point", n = 20), which draws just 20 evaluated points.

The function name or variable is not found

In curve(), an expression must use the variable named by xname, which is x unless you change it. If you set xname = "t", write the expression in terms of t.

Alternatives: base graphics versus ggplot2

Both approaches draw the same underlying curve; the decision is about the rest of your figure workflow.

Need Base R curve() ggplot2 geom_function()
Nothing extra to install Yes, part of the graphics package Requires install.packages(“ggplot2”)
Default range with no setting 0 to 1 for a new plot Taken from the plot’s x scale
Overlay a second function Second call with add = TRUE Add another geom_function() layer
Pass parameters to the function Write them in the expression, for example dt(x, df = 1) args = list(df = 1)
Keep the computed points Returned invisibly as list(x, y) after_stat(x) and after_stat(y)

Python users can find the grammar-of-graphics approach in plotnine.

Frequently asked questions

How do I plot a function in R?

Use curve(expr, from, to) in base R or ggplot() + xlim(a, b) + geom_function(fun = f) in ggplot2. The function must be vectorised.

How do I plot a function in R without data?

Neither tool needs a data frame. curve() evaluates the function itself between from and to, and ggplot2’s empty ggplot() with an xlim() supplies the range for geom_function().

How many points does R use to draw the curve?

101 equally spaced points by default in both curve() and ggplot2’s geom_function(), controlled by the argument n.

How do I plot two functions on the same graph in R?

In base R, draw the first with curve() and the second with curve(..., add = TRUE). In ggplot2, add a second geom_function() layer and map a label to colour to get a legend.

Can I plot a function I wrote myself?

Yes. Pass its name as expr or fun, or write an anonymous function such as (x) 0.5 * exp(-abs(x)) in ggplot2. It must return one value for each input x.

Can I plot a function that has parameters?

In ggplot2, supply them as a list to args, for example args = list(mean = 2, sd = .5). In curve(), put the parameters inside the expression.

Sources

Data: Argument map between base R curve() and ggplot2 geom_function()/stat_function()

Compares the arguments and defaults of base R curve() with ggplot2 geom_function() and stat_function() for plotting a function, compiled by hand from the two official reference pages.

Argument map between base R curve() and ggplot2 geom_function()/stat_function()
Taskcurve() argumentgeom_function() / stat_function() argumentDefault
Function to plotexprfunnone; must be vectorised
Range of xfrom, to (or xlim)xlim (or the plot x scale)curve: 0 to 1 for a new plot; ggplot2: NULL
Number of evaluation pointsnn101 in both
Add to an existing plotadd = TRUEadd another layercurve: add = FALSE
Extra parameters for the functionwrite inside exprargs = list(...)ggplot2: empty list
Rename the variablexnamenot applicable (use an anonymous function)curve: x
Line typetypegeom (for example geom = point)curve: type = l

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about Plot a Function in R: curve() and ggplot2 geom_function()

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →