Last active
April 6, 2019 11:09
-
-
Save mattansb/9ca3a430c20c1144ffcc2edd41fc5be5 to your computer and use it in GitHub Desktop.
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
library(tidyverse) | |
library(emmeans) | |
library(gganimate) | |
library(tweenr) | |
# Setup data -------------------------------------------------------------- | |
n <- 200 | |
df <- tibble(X1 = rnorm(n,100,15), | |
X2 = rnorm(n,30,5), | |
Y = -30*X1 + X1*X2 + 20 + rnorm(n)) | |
# Fit Model --------------------------------------------------------------- | |
fit <- lm(Y ~ X1*X2, df) | |
summary(fit) | |
emtrends(fit,~X2,'X1',cov.red = range) | |
# Get Data for the Frames ------------------------------------------------- | |
# Line Data | |
reg_line <- emmeans(fit,~X1*X2, | |
at = list(X1 = range(df$X1), | |
X2 = seq(min(df$X2),max(df$X2), length.out = 5))) %>% | |
summary() %>% | |
split(.$X2) %>% | |
tween_states(1,0, 'linear',50) | |
# Points Data | |
nframes <- length(unique(reg_line$.frame)) | |
step_size <- 5*diff(range(reg_line$X2))/(nframes-1) | |
filter_range <- function(df,frame,m_name,step_size){ | |
value <- reg_line[[m_name]][reg_line$.frame==frame][1] | |
subset(df, | |
df[[m_name]] > value - step_size & df[[m_name]] < value + step_size) | |
} | |
df_plot <- df %>% | |
list() %>% | |
rep(nframes) %>% | |
map2(seq_len(nframes),filter_range,m_name = 'X2', step_size = step_size) %>% | |
map2_dfr(seq_len(nframes),~mutate(.x,.frame = .y)) | |
# Looks good? | |
head(df_plot) | |
head(reg_line) | |
# Plot -------------------------------------------------------------------- | |
# setup | |
p <- ggplot(mapping = aes(X1,color = X2)) + | |
geom_point(aes(y = Y), data = df_plot, size = 1.5, alpha = .7) + | |
geom_line(aes(y = emmean), data = reg_line, size = 1) + | |
scale_color_viridis_c() + | |
theme_minimal() | |
# Static plot | |
p_static <- p + facet_wrap(~.frame) | |
# Animate | |
p_anim <- p + | |
transition_states(.frame) + | |
shadow_mark(T,T, exclude_layer = 2,color = 'gray', size = 1) | |
animate(p_anim,nframes = nrow(reg_line), duration = 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The beautiful result: