使用ggplot在多面图之间添加图

时间:2018-10-15 08:24:48

标签: r ggplot2

我有以下数据框:

structure(list(Z = c("1", "1", "1", "1", "1", "2", "2", "2", 
"2", "2", "3", "3", "3", "3", "3", "4", "4", "4", "4", "4"), 
    Y = c(0.12, 4, 1, 8, 0.25, 4, 0.06, 0.06, 8, 0.5, 0.12, 0.5, 
    0.06, 8, 16, 0.25, 0.12, 0.25, 4, 8), n = c(20L, 1L, 4L, 
    6L, 45L, 1L, 4L, 4L, 1L, 16L, 6L, 5L, 3L, 3L, 3L, 28L, 7L, 
    28L, 1L, 6L), X = c("E", "C", "C", "B", "A", "B", "E", "F", 
    "F", "A", "D", "F", "E", "B", "B", "B", "F", "E", "B", "D"
    ), value = c(14, 1, 1, 0, 45, 0, 3, 0, 0, 9, 0, 4, 3, 0, 
    0, 0, 1, 26, 0, 0)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -20L))

我使用以下代码创建这两个图:

library(ggplot2)
ggplot(test_data, aes(X, factor(Y), fill = value))+
  geom_tile(color = "white")+
  facet_wrap(~Z, ncol = 2)+
  coord_fixed()

enter image description here

ggplot(test_data, aes(factor(Y), n))+
  geom_col()+
  facet_wrap(~Z)+
  theme(axis.text.y = element_blank(),
        axis.title = element_blank(),
        axis.ticks.y = element_blank())+
  coord_flip()

enter image description here

我想要做的是将每个多面图并排放置,并缩短小图的宽度,如下所示:

enter image description here

我看到ggExtra程序包也有类似的东西,但是只适用于散点图。有没有办法以类似的方式在y轴上可视化每个类别的数量?

1 个答案:

答案 0 :(得分:0)

grid.arrange()包中有一个函数gridExtra(很好的解释[here])1。这使您可以绘制单独绘制的图,然后将它们排列在一致的网格中,并在需要时分别调整每个图的大小。为此,您需要分别绘制每个构面,然后将它们传递到包装中。

假设您的每个构面都称为A1(左上角),B4(左下角)。您的代码如下所示:

grid.arrange(
   grobs = c(Al:B4)
   widths = c(2, 1, 2, 1),
   layout_matrix = rbind(c(1, 2, 3, 4),
                         c(5, 6, 7, 8))
)

使用这种格式,您将单独标记图,以克服比例类型的差异。