将现有图添加到 facet_grid?

时间:2021-04-09 14:45:08

标签: r ggplot2

我有一个带有一些图的列表列数据框,例如

exdata <- diamonds %>% group_by(cut) %>% nest %>% crossing(dummy = 1:3) %>% 
+   mutate(plots = map(.x = data, ~ ggplot(.x, aes(x = x, y = y)) + geom_point()))
> exdata
# A tibble: 15 x 4
   cut       data                  dummy plots 
   <ord>     <list>                <int> <list>
 1 Fair      <tibble [1,610 × 9]>      1 <gg>  
 2 Fair      <tibble [1,610 × 9]>      2 <gg>  
 3 Fair      <tibble [1,610 × 9]>      3 <gg>  
 4 Good      <tibble [4,906 × 9]>      1 <gg>  
 5 Good      <tibble [4,906 × 9]>      2 <gg>  
 6 Good      <tibble [4,906 × 9]>      3 <gg>  
 7 Very Good <tibble [12,082 × 9]>     1 <gg>  
 8 Very Good <tibble [12,082 × 9]>     2 <gg>  
 9 Very Good <tibble [12,082 × 9]>     3 <gg>  
10 Premium   <tibble [13,791 × 9]>     1 <gg>  
11 Premium   <tibble [13,791 × 9]>     2 <gg>  
12 Premium   <tibble [13,791 × 9]>     3 <gg>  
13 Ideal     <tibble [21,551 × 9]>     1 <gg>  
14 Ideal     <tibble [21,551 × 9]>     2 <gg>  
15 Ideal     <tibble [21,551 × 9]>     3 <gg>  

现在 exdata$plots 中有 15 个 ggplots。我想模仿 ggplot2::facet_grid 的功能,其中我以指定的网格格式布置每个图。

特别是我想从左到右水平切割,然后向下读取字段虚拟作为垂直。

如果我从单个 df 构建图,我会执行类似 df %>% facet_grid(rows = dummy, columns = cut) 的操作。

是否可以将 facetgrid 与现有图一起使用,而不是基于从单个数据框创建图来使用此函数?如果是,如何?如果不是,我如何按照上述网格方式布置我的 ggplots?

1 个答案:

答案 0 :(得分:1)

library(patchwork)
exdata %>% 
  arrange(dummy) %>% 
  pull(plots) %>% 
  patchwork::wrap_plots(nrow = max(exdata$dummy))

我按 dummy 排序,以便所有 dummy == 1 图首先出现。如果您有一个完整的网格,这应该可以正常工作。如果缺少某些组合,我认为您将需要另一种解决方案,例如 geofacet 包,但这实际上只是 facet_grid 的变体,并且需要将数据放在一个数据框中。

enter image description here

相关问题