8

Is there a way to plot a polynomial function in ggplot without having to plot a datafame that contains selected points along the curve of interest? Say the equation is x^3 + x^2 + x + 5. I thought this could be done much in the same way that geom_abline can be used to add a straight line to a plot but am so far having no luck finding a way to do this. I checked the ggplot2 documentation but didn't see anything there I thought would help. geom_abline doesn't seem to extend past straight lines.

My end goal is to plot data from an independent dataset and use this polynomial curve as a "reference standard". The code below effectively plots the curve of interest but does so by plotting values along the curve, not by using the equation directly.

x <- 1:100
y <- x^3+x^2+x+5
dat <- as.data.frame(x,y)
ggplot(dat, aes(x,y)) + geom_point()
tsurudak
  • 592
  • 6
  • 14
  • Further details to Bes n's answer can be found at this SO post. http://stackoverflow.com/questions/5177846/equivalent-of-curve-for-ggplot – r.bot Apr 22 '15 at 20:05

1 Answers1

11

You're looking for stat_function(), I think:

x <- 1:100
dat <- data.frame(x,y=x^3+x^2+x+5)
f <- function(x) x^3+x^2+x+5
ggplot(dat, aes(x,y)) + 
    geom_point()+
    stat_function(fun=f, colour="red")

enter image description here

Ben Bolker
  • 192,494
  • 24
  • 350
  • 426