Skip to content

Instantly share code, notes, and snippets.

@bwiernik
Created October 30, 2020 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bwiernik/1e766c52127894f62b66da0b3f98654e to your computer and use it in GitHub Desktop.
Save bwiernik/1e766c52127894f62b66da0b3f98654e to your computer and use it in GitHub Desktop.
ggplot example individual + group change plot
library(tidyverse)
ind_data <- psych::bfi %>%
na.omit() %>%
filter(education %in% c(2, 4, 5)) %>%
select(A1:A5, education) %>%
group_by(education) %>%
slice(sample(1:n(), 40)) %>%
ungroup() %>%
rowid_to_column(".id") %>%
pivot_longer(A1:A5, names_to = "day", values_to = "score", names_pattern = "A(\\d)") %>%
mutate(education = factor(education, levels = c(2, 4, 5), labels = c("low", "med", "high")))
grp_data <- ind_data %>%
group_by(education, day) %>%
summarize(
n = n(),
mean = mean(score),
sd = sd(score),
lower = mean - qt(.975, n - 1) * sd / sqrt(n),
upper = mean + qt(.975, n - 1) * sd / sqrt(n)
) %>%
ungroup()
ind_data %>%
ggplot() +
theme_classic() +
# common aesthetics for all geoms
aes(x = day,
fill = education) +
# individual data lines
geom_line(aes(y = score, color = education, group = .id), alpha = .3,
position = position_jitter(width = 0)) + # remove position and width for the exact values
# group summary CI bands
geom_ribbon(
aes(y = mean, ymin = lower, ymax = upper, group = education),
data = grp_data,
alpha = .2,
size = 0
) +
# Group summary means
geom_line(aes(y = mean, color = education, group = education), data = grp_data, size = 1) +
geom_point(aes(y = mean, color = education, group = education), data = grp_data, size = 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment