I am trying to combine faceted boxplots with equally faceted lineplots, both of which should be properly aligned so that it is clear which plots belong together. I can actually achieve exactly what I want using ggpubr::ggarrange()
like this (I will call this a 2x4 layout, i.e. 2 rows by 4 columns):
In reality though I have a lot more classes than 4 (e.g. n_classes = 21
but the number may change depending on the underlying data) so that I would end up with a 2x21 plot that is unreadable. Now I want to split the entire 2x21 plot into pages of 2x4 plots, ideally while preserving the common legend so that point sizes stay comparable across pages. What's the best approach to do this?
[I saw that ggarrange()
does have multi page support (see http://www.sthda.com/english/articles/24-ggpubr-publication-ready-plots/81-ggplot2-easy-way-to-mix-multiple-graphs-on-the-same-page/#annotate-the-arranged-figure) but I think this does not work in my case because of the faceting I am using. There does not seem to be a way of telling ggarrange()
that p_top
and p_bottom
consist of 4 columns each.]
Code used
library(tidyverse)
library(ggpubr)
# create dummy data with two groups (period and class)
n <- 1e4
n_classes <- 4
p_classes <- sample(seq(0.1, 0.9, length.out = n_classes))
dt <- tibble(
period = sample(c("161", "162", "171", "172"), size = n, replace = TRUE),
class = sample(LETTERS[1:n_classes], size = n, prob = p_classes, replace = TRUE),
value = sample(0:20, size = n, replace = TRUE)
)
# total counts by period and group
dt2 <- dt %>%
group_by(period, class) %>%
summarise(total = n()) %>%
left_join(dt, by = c("period", "class"))
# plot the total counts by period (faceted by class)
p_top <- ggplot(dt2, aes(x = period, y = total, group = 1)) +
facet_wrap(~ class, nrow = 1, scales = "free_y") +
theme_bw() +
theme(strip.background = element_blank(),
strip.text.x = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
geom_line() +
geom_point(aes(size = total), shape = 21, fill = "white") +
scale_y_continuous(limits = c(0, NA))
# values boxplot by period (faceted by class)
p_bottom <- ggplot(dt2, aes(x = period, y = value)) +
facet_wrap(~ class, nrow = 1, scales = "fixed") +
theme_bw() +
theme(plot.margin = unit(c(-0.6, 1, 1, 1), units = "lines")) +
geom_boxplot(width = 0.7, outlier.shape = NA, fill = "lightgray")
# arrange top and bottom plots
ggarrange(p_top, p_bottom, nrow = 2, align = "v",
heights = c(1, 3),
common.legend = TRUE, legend = "bottom")
Created on 2018-07-02 by the reprex package (v0.2.0).