1

I've been trying to plot some data and add a third order polynomial trend line. I'm using the lm() and coef() functions to obtain a model for my data and then plot with ggplot.

Here is the relevant code:

Bytes is the name of my dependent variable (y). Resolution is the name of my independent variable (x).

model = lm(Bytes~poly(Resolution, 3), averaged_frame) print(coef(model)) library(ggplot2) plot = ggplot(averaged_frame, mapping = aes(x = Resolution, y = Bytes)) + geom_point() + stat_smooth(method="lm", formula = y~poly(x, 3), se = FALSE) 

However, when I take the coefficients from print(coef(model)):

 (Intercept) poly(Resolution, 3)1 poly(Resolution, 3)2 poly(Resolution, 3)3 0.3392046 0.3686154 0.2504288 0.1274490 

And transpose them into a function:

f(x)=0.1274490x^3+0.2504288x^2+0.3686154x+0.3392046 

And graph it, it looks completely different to the plot on ggplot.

enter image description here

enter image description here

I'm wondering what I am doing wrong here or how I might get an equation from the line in ggplot.

1
  • You should use raw = TRUE in poly. That's why you get a different curve. Commented May 13, 2023 at 5:54

1 Answer 1

0

Here is an example with the ggpmisc package. This is for an order one regression, you have to adapt to your case.

df <- data.frame(x = c(1:100)) df$y <- 20 + 30 * df$x + rnorm(100, sd = 80) library(ggpmisc) my_formula <- y ~ x myformat <- "y = %s + %s x --- R²: %s" ggplot(df, aes(x, y)) + geom_point() + geom_smooth(method = "lm", formula = my_formula, se = FALSE) + stat_poly_eq( formula = my_formula, output.type = "numeric", mapping = aes( label = sprintf( myformat, formatC(after_stat(coef.ls)[[1]][[1, "Estimate"]]), formatC(after_stat(coef.ls)[[1]][[2, "Estimate"]]), formatC(stat(r.squared))), ), vstep = 0.1, size = 10 ) 

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.