Skip to content

Instantly share code, notes, and snippets.

@jthomasmock
Last active May 16, 2018 12:40
Show Gist options
  • Save jthomasmock/568f04e123622d44337584111bd682f5 to your computer and use it in GitHub Desktop.
Save jthomasmock/568f04e123622d44337584111bd682f5 to your computer and use it in GitHub Desktop.
dumbell_plot overlay
library(tidyverse)
# generate random data
xdf <- data.frame(id = rep(1:100, 2),
risk = c(rnorm(100, mean = 10, sd = 1), rnorm(100, mean = 7, sd = 1)),
year = c(rep(2016, 100), rep(2017, 100))) %>%
mutate(id = factor(id),
year = factor(year))
# summarize data
x_summary <- xdf %>%
group_by(year) %>%
summarize(risk_mean = mean(risk))
# create a dumbell plot
(db_plot <- xdf %>%
ggplot(aes(x = year, y = risk)) +
geom_line(aes(group = id), color = "grey") +
geom_point(color = "grey") +
geom_point(data = x_summary, aes(x = year, y = risk_mean), size = 4, color = "blue") +
geom_line(data = x_summary, aes(x = year, y = risk_mean), group = 1, size = 2, color = "blue") +
labs(x = NULL,
y = "Risk Factor") +
theme_light() +
theme(axis.title.y = element_text(size = 12)))
# create a boxplot + jitter plot
(db_boxplot <- xdf %>%
ggplot(aes(x = year, y = risk)) +
geom_jitter(color = "grey", width = 0.2) +
geom_boxplot(aes(group = year), alpha = 0.2, width = 0.4) +
labs(x = NULL,
y = "Risk Factor") +
theme_light() +
theme(axis.title.y = element_text(size = 12)))
ggsave("dbplot.png", db_plot, height = 8, width = 8, units = "cm", dpi = 1000)
ggsave("db_boxplot.png", db_boxplot, height = 8, width = 8, units = "cm", dpi = 1000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment