我正在尝试将多面箱线图与等面线图结合起来,两者都应该正确对齐,以便清楚哪些图属于一起。我实际上可以像这样实现我想要ggpubr::ggarrange()
的(我称之为 2x4 布局,即 2 行乘 4 列):
实际上,虽然我有比 4 更多的类(例如n_classes = 21
,但数量可能会根据基础数据而变化),所以我最终会得到一个不可读的 2x21 绘图。现在我想将整个 2x21 绘图拆分为 2x4 绘图的页面,理想情况下,同时保留常见的图例,以便点大小在页面之间保持可比性。这样做的最佳方法是什么?
[我看到ggarrange()
确实有多页支持(见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)但我认为这在我的情况下不起作用,因为我正在使用分面。似乎没有办法说明ggarrange()
这一点p_top
,p_bottom
每列由 4 列组成。]
使用的代码
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")
由reprex 包(v0.2.0)于 2018 年 7 月 2 日创建。