多面和对齐图的多页输出

时间:2018-07-02 14:15:43

标签: r ggplot2 ggpubr

我正在尝试将多面的箱形图与同等多面的线图组合在一起,这两个图应正确对齐,以便清楚地知道哪些图属于在一起。我实际上可以像这样使用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_topp_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 package(v0.2.0)于2018-07-02创建。

0 个答案:

没有答案