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

11,418
# 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))
Share:
11,418
user4631839
Author by

user4631839

Updated on August 08, 2022

Comments

  • user4631839
    user4631839 over 1 year

    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?

  • Alex A.
    Alex A. about 9 years
    You could also do qplot(...) + stat_function(...).