【问题标题】:Print out plots for each group in list column打印列表列中每个组的图
【发布时间】:2021-09-27 20:58:40
【问题描述】:

带有一些图的列表列:

mydiamonds <- diamonds %>% 
  group_by(cut, color) %>% 
  nest %>% 
  mutate(plots = map(data, ~ ggplot(.x, aes(x = x, y = price)) + geom_point()))

mydiamonds
# A tibble: 35 × 4
# Groups:   cut, color [35]
   cut       color data                 plots 
   <ord>     <ord> <list>               <list>
 1 Ideal     E     <tibble [3,903 × 8]> <gg>  
 2 Premium   E     <tibble [2,337 × 8]> <gg>  
 3 Good      E     <tibble [933 × 8]>   <gg>  
 4 Premium   I     <tibble [1,428 × 8]> <gg>  
 5 Good      J     <tibble [307 × 8]>   <gg>  
 6 Very Good J     <tibble [678 × 8]>   <gg>  
 7 Very Good I     <tibble [1,204 × 8]> <gg>  
 8 Very Good H     <tibble [1,824 × 8]> <gg>  
 9 Fair      E     <tibble [224 × 8]>   <gg>  
10 Ideal     J     <tibble [896 × 8]>   <gg>  
# … with 25 more rows

我想使用facet_wrap() 打印出每个图,以便它们一起出现在一个图表中。但我什至还不能一张一张地打印出来。试过了:

mydiamonds %>% map(plots, ~print(.x))
Error in as_mapper(.f, ...) : object 'plots' not found

我希望从 sn-p 中清楚我想要做什么 - 只需打印出每个图(这是在 Rmd 代码块内,所以会很好地打印出来)

奖励 - 假设我知道如何将它们打印出来,是否可以使用 facet_wrap() 将它们放到单个图表上,其中标题为 paste0(cut, "|", color)?

【问题讨论】:

    标签: r ggplot2 purrr


    【解决方案1】:

    plots 列在数据外不可见

    library(ggplot2)
    library(dplyr)
    library(purrr)
    mydiamonds %>%
       ungroup %>%
       # either pull the column
       # or use `.$plots`
       pull(plots) %>%
       map(print)
    

    或使用walk

    mydiamonds %>%
       ungroup %>%
       pull(plots) %>%
       walk(print)
    

    我们可以使用ggarrange 将所有情节放到一个页面中,但它太小了

    library(ggpubr)
    mydiamonds %>%
        ungroup %>%
        pull(plots) %>%
        ggarrange(plotlist = ., nrow = 5, ncol = 7)
    

    或者最好导出到pdf

    mydiamonds %>%
        ungroup %>%
        pull(plots) %>%
        ggarrange(plotlist = ., nrow = 1, ncol = 1) %>%
        ggexport(., filename="plots.pdf")
    

    检查输出pdf

    【讨论】:

    • 我们为什么要在这里解组?
    • @DougFir 这里没有必要,但我认为当我们循环遍历每个元素时,组属性是不必要的
    • 如果我能跑一英里,使用facet_wrap() 将它们全部放入一个图表中会很困难吗?
    • 谢谢!我的真实数据将只有 8 个图表,如果我们在取消分组 %&gt;% head %&gt;% 之后添加一行以仅返回 5 或 6 行,那么将如何使用 facet_wrap?我尝试使用mydiamonds %&gt;% ungroup %&gt;% head %&gt;% pull(plots) %&gt;% facet_wrap(vars('plots')) 给出错误
    • @DougFir 这是您生成的单独图。 facet_wrap 应在单个数据图中使用。你可能需要pull(plots) %&gt;% ggarrange(plotlist = ., nrow = 3, ncol = 2)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多