R: Add a curve,with my own equation, to an x,y scatterplot

user4631839 picture user4631839 · Mar 10, 2015 · Viewed 10.6k times · Source

I want to add a curve with the following equation to an x,y scatterplot: y<-(105+0.043(x^2-54x)). Is it possible within the plot() function? Also, if I use qplot instead (ggplot2) is there a way to draw this curve?

Answer

Gregor Thomas picture Gregor Thomas · Mar 10, 2015
# data for scatterplot
x = rnorm(10, sd = 10)
y = (105 + 0.043 * (x^2 - 54 * x)) + rnorm(10, sd = 5)

Base plotting

plot(x, y)
curve(105 + 0.043 * (x^2 - 54 * x), add = T)

For ggplot, we need a data.frame

dat = data.frame(x = x, y = y)

ggplot(dat, aes(x , y)) + 
    geom_point() +
    stat_function(fun = function(x) 105 + 0.043 * (x^2 - 54 * x))