代码之家  ›  专栏  ›  技术社区  ›  Joe

在映射函数中迭代应用ggplot函数

  •  3
  • Joe  · 技术社区  · 8 年前

    library(tidyverse)
    
    mtcars %>% 
      select(wt, disp, hp) %>% 
      map(., function(x)
        ggplot(aes(x = x)) + geom_histogram()
    )
    

    我可以用for循环(h/t)来完成这项任务,但我正试图在tidyverse中做同样的事情。

    foo <- function(df) {
      nm <- names(df)
      for (i in seq_along(nm)) {
    print(
      ggplot(df, aes_string(x = nm[i])) + 
      geom_histogram()) 
      }
    }
    
    mtcars %>% 
      select(wt, disp, hp) %>% 
      foo(.)
    

    2 回复  |  直到 8 年前
        1
  •  5
  •   acylam    8 年前

    类似的方法也可以:

    library(purrr)
    library(dplyr)
    mtcars %>% 
      select(wt, disp, hp) %>% 
      names() %>%
      map(~ggplot(mtcars, aes_string(x = .)) + geom_histogram())
    

    mtcars %>% 
      select(wt, disp, hp) %>% 
      {map2(list(.), names(.), ~ ggplot(.x, aes_string(x = .y)) + geom_histogram())}
    
        2
  •  2
  •   CPak    8 年前

    purrr::map ,您可以融化数据帧,然后根据变量名将其拆分为数据帧列表

    library(reshape2)
    library(dplyr)
    library(ggplot2)
    library(purrr)
    
    melt(mtcars) %>%
      split(.$variable) %>%
      map(., ~ggplot(.x, aes(x=value)) + 
                geom_histogram())
    

    您也可以使用 ggplot2::facet_wrap 一次就把它们全部标出来

    library(reshape2)
    library(dplyr)
    library(ggplot2)
    
    melt(mtcars) %>% 
      ggplot(., aes(x=value, label=variable)) + 
      geom_histogram() + 
      facet_wrap(~variable, nrow=ncol(mtcars))