简体   繁体   English

迭代地在地图函数中应用ggplot函数

[英]iteratively apply ggplot function within a map function

I would like to generate a series of histograms for all variables in a dataset, but I am clearly not preparing the data correctly for use in the map function. 我想为数据集中的所有变量生成一系列直方图,但我显然没有正确地准备数据以用于map函数。

library(tidyverse)

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

I can accomplish this task with a for loop (h/t but am trying to do the same thing within the tidyverse. 我可以通过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(.)

Any help is greatly appreciated. 任何帮助是极大的赞赏。

Something like this would also work: 这样的东西也会起作用:

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

or: 要么:

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

To use purrr::map , you could melt your data frame, and then split it based on the variable name into a list of data frames 要使用purrr::map ,您可以融化数据框,然后根据变量名将其拆分为数据框列表

library(reshape2)
library(dplyr)
library(ggplot2)
library(purrr)

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

You can also use ggplot2::facet_wrap to plot them all at once 您也可以使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM