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()
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With