Add Polynomial Regression Line to Plot in R (2 Examples) | Base R & ggplot2 | lm() & stat_smooth()

preview_player
Показать описание
R code of this video:

x <- rnorm(200)
y <- rnorm(200) + 0.2 * x^3
head(data) # Print example data frame

my_mod <- lm(y ~ poly(x, 4), # Estimate polinomial regression model
data = data)
summary(my_mod) # Summary statistics of polynomial regression model

plot(y ~ x, data) # Draw Base R plot

lines(sort(data$x), # Draw polynomial regression curve
fitted(my_mod)[order(data$x)],
col = "red",
type = "l")

library("ggplot2")

ggp <- ggplot(data, aes(x, y)) + # Create ggplot2 scatterplot
geom_point()
ggp # Draw ggplot2 scatterplot

ggp + # Add polynomial regression curve
stat_smooth(method = "lm",
formula = y ~ poly(x, 4),
se = FALSE)

ggp + # Regression curve & confidence band
stat_smooth(method = "lm",
formula = y ~ poly(x, 4))

Follow me on Social Media:

Рекомендации по теме
Комментарии
Автор

Joachim, you must have a crystal ball or the universe is more magical than we imagine. Right now I am working on this same subject. Is is unbelieavable, your last videos on R were able to answer my questions on the spot.Thank you so very much!!

johneagle
Автор

Love the video! Can you do a video that's like this one but has a few dummy variables so that there's multiple lines plotted? Thanks!

gezltft
Автор

to build a simulation in the case of polynomial regression I need the true signal, but where should I get the data from training or test data?

alessandrorosati
Автор

I am just getting loads of vertical red lines, like a barcode or something.

xb
Автор

Hi Joachim, danke für dein Video, sehr hilfreich! Wie müsste man den Code anpassen, wenn man einen fixen Intercept von (0/0) hat?
LG

tilmannstrepp