Created
November 6, 2021 00:15
-
-
Save maxdrohde/0882eb8cbca3b75bd39c501fef737007 to your computer and use it in GitHub Desktop.
OLS anim
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
gen_dataset <- function(){ | |
b0 <- 3 | |
b1 <- 7 | |
x <- 1:10 | |
linear_predictor <- b0 + b1*x | |
y <- rnorm(n = length(linear_predictor), mean=linear_predictor, sd=8) | |
df <- tibble(x,y) | |
# Fit OLS model | |
ols_model <- lm(y ~ x, data=df) | |
# Print results | |
results <- broom::tidy(ols_model) | |
# Save model parameters | |
b0_estimate <- results[[1,2]] | |
b1_estimate <- results[[2,2]] | |
df$b0 <- b0 | |
df$b1 <- b1 | |
df$b0_estimate <- b0_estimate | |
df$b1_estimate <- b1_estimate | |
return(df) | |
} | |
dfs <- map_df(1:10, ~gen_dataset(), .id = "dataset") | |
gif <- | |
dfs %>% | |
ggplot() + | |
aes(x=x, y=y) + | |
geom_point() + | |
geom_abline(aes(intercept=b0, slope=b1), color="blue", linetype=2) + # True line | |
geom_abline(aes(intercept=b0_estimate, slope=b1_estimate), color="red") + # Estimated line | |
theme_bw() + | |
transition_manual(dataset) + | |
labs(title="Blue: True regression line\nRed: Fitted regression line") | |
anim <- animate(gif, | |
duration=8, | |
height = 6, | |
width = 6, | |
units = "in", | |
res = 300, | |
renderer =gifski_renderer()) | |
anim_save(animation = anim, filename = "ols_anim.gif") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment