iteratively apply ggplot function within a map function

送分小仙女□ 提交于 2020-01-14 19:01:30

问题


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.

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.

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.


回答1:


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



回答2:


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

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

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

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


来源:https://stackoverflow.com/questions/46570609/iteratively-apply-ggplot-function-within-a-map-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!