1
votes

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 filter down my giant dataframe so I just have one group like this:

df <- data.frame(group = c("la", "li", "lo"), 
                 x_variable = c(20000, 32000, 48000), 
                 y_variable = c( 175,  200, 250),
                 coef_a = c(0.000000308, 0.000000308, 0.000000308),
                 coef_b = c(-0.0168, -0.0168, -0.0168), 
                 coef_c = c(437, 437, 437))  

Here's what I tried:

ggplot(df, aes(x = x_variable, y = y_variable)) + 
 geom_point() +
 stat_function(fun = ~ .coef_a * .x^2 + .coef_b * .x + .coef_c)  

I get

Warning message: Computation failed in stat_function(): object '.coef_a' not found

I thought using the . would refer back to the dataframe. What am I missing?

1

1 Answers

0
votes

I would suggest defining your function elsewhere so you can then use the standard args = argument of stat_function.

f <- function(x, coef_a, coef_b, coef_c) coef_a * x^2 + coef_b * x + coef_c

ggplot(df, aes(x = x_variable, y = y_variable)) + 
    geom_point() +
    stat_function(fun = f, args = list(coef_a = df$coef_a, coef_b = df$coef_b, coef_c = df$coef_c)) 

From my understanding, not using coef_a, coef_b, and coef_c in the aes function means you need to reference them explicitly. Hope this helps.