Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plot polynomial curve in ggplot using equation, not data points [duplicate]

Tags:

r

ggplot2

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()
like image 382
tsurudak Avatar asked Apr 22 '15 19:04

tsurudak


1 Answers

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

like image 189
Ben Bolker Avatar answered Sep 21 '22 12:09

Ben Bolker