Last active
November 13, 2017 00:39
-
-
Save JoGall/8e99e30a21146f82ab21e79745e6b44b to your computer and use it in GitHub Desktop.
Lexis lifeline ggplot
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(ggplot2) | |
library(dplyr) | |
library(scales) | |
# SAMPLE DATA | |
set.seed(123) | |
# get all dates in a range | |
start_date <- as.Date("2017-01-01") | |
end_date <- as.Date("2017-06-01") | |
dates <- seq(start_date, end_date, 1) | |
# sample random start date with random duration 1-100 | |
d <- data.frame(start = sample(dates, 100, replace=T), | |
duration = round(runif(100, 1, 100))) | |
# end date as start date + duration | |
d$end <- d$start + d$duration | |
d <- d %>% | |
# infer whether active | |
mutate(active = if_else(end >= end_date, 1, 0)) %>% | |
# censor end date | |
mutate(end = if_else(end > "2017-06-01", as.Date("2017-06-01"), end)) %>% | |
# recalculate duration | |
mutate(duration = end - start) | |
# GGPLOT | |
mytheme <- theme_bw() + | |
theme(aspect.ratio=0.5, | |
axis.title = element_text(size = 14), | |
axis.text.y = element_text(size = 14), | |
axis.text.x = element_text(angle = 45, hjust = 1, size = 13), | |
legend.position = c(0, 1), | |
legend.justification = c(0, 1), | |
legend.box.margin=margin(c(20,20,20,20)), | |
legend.title = element_blank(), | |
legend.text = element_text(size = 13), | |
legend.background = element_rect(fill = "grey95")) | |
ggplot(d) + | |
geom_segment(aes(x = start, y = 0, xend = end, yend = duration, colour = as.factor(active)), alpha = 0.3) + | |
geom_point(aes(x = end, y = duration, colour = as.factor(active)), alpha = 0.6, size = 2) + | |
scale_color_manual(name = "", labels = c("Inactive", "Active"), breaks = c(0, 1), values = c("grey30", "purple")) + | |
scale_x_date(date_breaks = "1 month", date_minor_breaks = "1 month", labels = date_format("%b %y")) + | |
scale_y_continuous(limits = c(0, 100), expand=c(0,0)) + | |
xlab("") + | |
ylab("Time (days)") + | |
mytheme |
Author
JoGall
commented
Oct 26, 2017
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment