【问题标题】:Problem with passing ggplot titles in a purrr loop (list-columns)在 purrr 循环(列表列)中传递 ggplot 标题的问题
【发布时间】:2020-10-01 01:23:25
【问题描述】:

我正在使用带有 purr 地图的列表列方法来生成带有 ggplot 的一系列图(我确实阅读了 @aosmith 的优秀帖子,在这里 printing ggplot with purrr map 和她的博客 https://aosmith.rbind.io/2018/08/20/automating-exploratory-plots/ 上)。但是,我遇到的问题是如何在地图循环中将单个标题传递给这些地块。我知道我可以在稍后阶段使用 plotgrid 等或 mapply 等来做到这一点,但我想知道为什么在使用 mutate 生成情节时它不起作用。

这是一个例子:

# Note that I am using dplyr 1.0.0 and R 4.0

library(tidyverse)

# Vector with names for the plots  

myvar <- c("cylinderA", "cylinderB", "cylinderC")
myvar <- set_names(myvar)

# Function to plot the plots
myPlot <- function(dataaa, namesss){
    ggplot(data = dataaa) +
        aes(x = disp, y = qsec) +
        geom_point() +
        labs(title = namesss)
}

# List-columns with map2 to iterate over split dataframe and the vector with names

mtcars %>% 
    group_by(cyl) %>% 
    nest() %>% 
    mutate(plots = map2(data, myvar, myPlot))

这会产生指向向量回收问题的错误,但我的数据列表和 myvar 向量的长度相同。

Error: Problem with `mutate()` input `plots`. x Input `plots` can't be recycled to size 1. ℹ Input `plots` is `map2(data, myvar, myPlot)`. ℹ Input `plots` must be size 1, not 3. ℹ The error occured in group 1: cyl = 4.

此外,当我将 map2 与列表列和我的向量与名称一起单独使用时,它可以按预期工作...

test <- mtcars %>% 
    group_by(cyl) %>% 
    nest()

map2(test$data, myvar, myPlot) # This works

任何对此行为的解释以及如何在 purrr/dplyr 方法中修复它都将不胜感激:-)

kJ

【问题讨论】:

    标签: r ggplot2 tidyverse purrr


    【解决方案1】:

    只需在nest 后面加上ungroup

    library(tidyverse)
    
    # Vector with names for the plots  
    
    myvar <- c("cylinderA", "cylinderB", "cylinderC")
    myvar <- set_names(myvar)
    
    # Function to plot the plots
    myPlot <- function(dataaa, namesss){
      ggplot(data = dataaa) +
        aes(x = disp, y = qsec) +
        geom_point() +
        labs(title = namesss)
    }
    
    # List-columns with map2 to iterate over split dataframe and the vector with names
    
    mtcars %>% 
      group_by(cyl) %>% 
      nest() %>% 
      ungroup() %>% 
      mutate(plots = map2(data, myvar, myPlot))
    #> # A tibble: 3 x 3
    #>     cyl data               plots 
    #>   <dbl> <list>             <list>
    #> 1     6 <tibble [7 x 10]>  <gg>  
    #> 2     4 <tibble [11 x 10]> <gg>  
    #> 3     8 <tibble [14 x 10]> <gg>
    

    reprex package (v0.3.0) 于 2020-06-11 创建

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 2023-02-22
      相关资源
      最近更新 更多