【问题标题】:iteratively apply ggplot function within a map function在 map 函数中迭代地应用 ggplot 函数
【发布时间】:2018-03-16 04:28:34
【问题描述】:

我想为数据集中的所有变量生成一系列直方图,但我显然没有正确准备数据以用于 map 函数。

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(.)

非常感谢任何帮助。

【问题讨论】:

  • 您需要为每个图创建不同的图,还是分面解决方案可以?

标签: r ggplot2 tidyverse purrr


【解决方案1】:

要使用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))

【讨论】:

    【解决方案2】:

    类似的方法也可以:

    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())}
    

    【讨论】:

      猜你喜欢
      • 2013-05-20
      • 1970-01-01
      • 2020-10-18
      • 2021-05-22
      • 2022-01-05
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2018-01-19
      相关资源
      最近更新 更多