2

I have the coefficients for a curve and would like to draw the curve in ggplot2. My formula is just a polynomial:

y = a * x^2 + b * x + c  

I have these coefficients:

a <-  0.000000308  
b <- -0.0168  
c <-  437  

I don't know if these points will fall near the line, but say we are plotting this df:

df <- data.frame(group = c("a", "b", "c"), 
                 x_variable = c(20000, 32000, 48000), 
                 y_variable = c( 175,  200, 250))  

Here's what I tried:

ggplot(df, aes(x = x_variable, y = y_variable)) + 
 geom_point() +
 # this next line doesn't work, is it close?
 # geom_smooth(method = 'lm', formula = y ~ 0.000000308 * x^2 + -0.0168 * x + 437)    
Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
Nazer
  • 3,654
  • 8
  • 33
  • 47
  • 1
    [Plot a function with ggplot, equivalent of curve()](https://stackoverflow.com/questions/5177846/plot-a-function-with-ggplot-equivalent-of-curve) – Henrik Jun 16 '20 at 18:36

3 Answers3

2

One option is to use stat_function which applies a function along a grid of x values that fits the plotting area:

ggplot(df, aes(x = x_variable, y = y_variable)) + 
  geom_point() +
  stat_function(fun = function(x){0.000000308 * x^2 + -0.0168 * x + 437})

enter image description here

Ian Campbell
  • 23,484
  • 14
  • 36
  • 57
0

Not sure if I'm totally misunderstanding your question, but I would just create some sample points:

library(data.table)
DT = data.table(x=1:100000)
DT[,y := a * x^2 + b * x + c]
ggplot(DT,aes(x=x,y=y))+geom_smooth()
webb
  • 4,180
  • 1
  • 17
  • 26
0

Generate a function grid first and then plot the function along with your points:

library(ggplot2)

a <-  0.000000308  
b <- -0.0168  
c <-  437 

grid <- data.frame( x = seq(15000, 60000, 1))
grid$y <- a*grid$x^2 + b*grid$x +c

points <- data.frame(x_variable = c(20000, 32000, 48000), 
                     y_variable = c( 175,  200, 250))

ggplot() +
  geom_line(data = grid, aes(x,y), color = "red") +
  geom_point(data = points, aes(x_variable,y_variable))
slava-kohut
  • 4,203
  • 1
  • 7
  • 24