make_fold_timeline_plot <- function(
dat,
facet_rows = "Pathway",
trans = "identity",
color_by = NULL,
colors = colors_effect,
size_boost = 1
) {
origin <- do.call(trans, list(1))
dat <- (dat |>
mutate(Fold_trans = do.call(trans, list(Fold))) |>
mutate(
Fold_Amp = ifelse(
max(Fold_trans, na.rm = TRUE) - min(Fold_trans, na.rm = TRUE) != 0,
max(Fold_trans, na.rm = TRUE) - min(Fold_trans, na.rm = TRUE),
mean(Fold_trans, na.rm = TRUE)
) *
0.1,
.by = all_of(c(facet_rows, "Stage"))
))
timeline <- (ggplot(dat) +
{
if (is.null(color_by)) aes(x = Gene, color = Fold >= 1) else aes(x = Gene, color = .data[[color_by]])
} +
geom_linerange(aes(ymax = Fold_trans), ymin = origin, linewidth = 2 + (size_boost * 0.5)) +
geom_hline(yintercept = origin, linewidth = 0.3, linetype = "dotted") +
geom_text(
aes(
label = str_c(round(Fold, 2), stars.pval(p.value) |> str_replace(fixed("."), ""), sep = " "),
y = ifelse(Fold_trans > origin, Fold_trans + Fold_Amp, Fold_trans - Fold_Amp),
hjust = ifelse(Fold > 1, 0, 1)
),
vjust = 0.5,
angle = 0,
size = 2 + (size_boost * 0.25),
check_overlap = TRUE
) +
scale_color_manual(" ", values = colors) +
scale_y_continuous(breaks = c(0, 1, 2, 3), expand = expansion(mult = 1.01 * (1 + (size_boost / 100)))) +
scale_x_discrete(expand = expansion(add = 1 * size_boost), limits = \(x) rev(x)) +
labs(
x = "",
y = ifelse(trans != "identity", str_glue("Fold Change *({trans} scale)*"), "Fold Change")
) +
coord_flip() +
facet_grid(
vars(.data[[facet_rows]]),
vars(Stage),
scales = "free_y",
space = "free_y",
labeller = label_wrap_gen(width = 12, multi_line = TRUE)
) +
{
if (!is.null(color_by)) guides(color = guide_legend(title = color_by))
} +
theme(
legend.position = ifelse(is.null(color_by), "none", "bottom"),
axis.text.x = element_blank(),
axis.title.x = element_markdown(size = 9),
axis.text.y = element_text(size = 7),
strip.text = element_text(size = 5 * size_boost),
plot.title = element_markdown(size = 9, face = "plain", vjust = 1, hjust = 0.5)
))
return(timeline)
}