【问题标题】:How to use purrr::pmap to plot multiple ggplot in nested.data.frame如何使用 purrr::pmap 在nested.data.frame 中绘制多个ggplot
【发布时间】:2018-05-09 00:01:17
【问题描述】:

我有一些关于 purrr::pmap 在nested.data.frame 中制作多个ggplot 绘图的问题。

我可以通过使用 purrr::map2 毫无问题地运行以下代码,并且可以在 nested.data.frame 中制作多图(2 个图)。

作为一个例子,我在 R 中使用了 iris 数据集。

library(tidyverse)

iris0 <- iris
iris0 <-
iris0 %>%  
group_by(Species) %>%  
nest() %>%  
mutate(gg1 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point())) %>%
mutate(gg2 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point())) %>%
mutate(g = purrr::map2(gg1, gg2, ~ gridExtra::grid.arrange(.x, .y)))

但是,当我想绘制超过 2 个图时,我无法使用 purrr::pmap 解决,如下面的代码。

iris0 <-  
iris0 %>%  
group_by(Species) %>%  
nest() %>%  
mutate(gg1 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point())) %>%
mutate(gg2 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point())) %>%
mutate(gg3 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Length)) + geom_point())) %>%
mutate(g = purrr::pmap(gg1, gg2,gg3, ~ gridExtra::grid.arrange(.x, .y, .z)))

> Error in mutate_impl(.data, dots) : Index 1 is not a length 1 vector

nested.data.frame 中是否有解决此问题的方法? 请给我一些建议或答案。

【问题讨论】:

    标签: r ggplot2 purrr


    【解决方案1】:

    purrr::pmap 接受(至少)两个参数:

     pmap(.l, .f, ...)
    

    在哪里

      .l: A list of lists. The length of '.l' determines the number of
          arguments that '.f' will be called with. List names will be
          used if present.
      .f: A function, formula, or atomic vector.
    

    此外,.x.y 仅适用于两个参数,但(在同一个手册页中)它显示为 For more arguments, use '..1', '..2', '..3' etc

    为了可读性(和一点效率),我将对mutate 的所有单独调用合并为一个;如果需要,您可以将它们分开(特别是如果代码比您在这个简化示例中显示的更多):

    library(dplyr)
    library(tidyr)
    library(purrr)
    library(ggplot2)
    iris0 <- iris %>%  
      group_by(Species) %>%  
      nest() %>%  
      mutate(
        gg1 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Sepal.Width)) + geom_point()),
        gg2 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Width)) + geom_point()),
        gg3 = purrr::map(data, ~ ggplot(., aes(Sepal.Length, Petal.Length)) + geom_point()),
        g = purrr::pmap(list(gg1, gg2, gg3), ~ gridExtra::grid.arrange(..1, ..2, ..3))
      )
    

    【讨论】:

    • 感谢您的快速解答!我可以解决我的问题!我忽略了 purrr::pmap 需要列表列表。谢谢。
    • 如果它解决了您的问题,请选择答案左侧的复选标记“接受”它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多