9

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
  • 602
  • 7
  • 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

12

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

If you have a very wiggly function you should increase the n (number of evaluation points) from its default value of 101 to something larger (say, n = 1000; anything much larger than this will probably be higher resolution than you can see on a screen anyway).

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • When I use stat_function my curve is more connected line segments than a smooth curve... any idea how I can fix that? – Doc Brown May 22 '18 at 10:44
  • 1
    the default number of evaluation points is `n=101`. You could try increasing that if your function is very wiggly. Otherwise, try asking a new question with a reproducible example ...? – Ben Bolker May 22 '18 at 12:23
  • @Ben Bolker Thanks! Setting n = 1000 does the trick :-) – Doc Brown May 28 '18 at 08:20