ggplot2: make a list of plots from list of dataframes using purrr::map()

35 Views Asked by At

Have the following lisf of dfs:

df_to_plot <- list(list1 = data.frame(list1 = letters[seq(1, 6)],
                                      b = rnorm(n = 6, mean = 7, 1)),
                   list2 = data.frame(list2 = letters[seq(1, 6)], 
                                      b = rnorm(n = 6, mean = 8, 2)),
                   list3 = data.frame(list3 = letters[seq(1, 6)], 
                                      b = rnorm(n = 6, mean = 8, 2)))

And I sue a list of strings to identify the dataframes I want to plot

col_list <- c('list1', 'list3')

Now I made a function to do the plots and use map() to loop through the list and return a list of plots

plots <- function(df_list, col_list){
  x = ggplot(df_list, aes(x = as.character(.data[[col_list]]), 
                          y = as.numeric(.data[['b']]), 
                          fill = as_factor(.data[[col_list]]))) +
               geom_col()
}

map(col_list, \(var_list) plots(df_to_plot, var_list))

But I get the following error

Error in `map()`:
ℹ In index: 1.
Caused by error in `fortify()`:
! `data` must be a <data.frame>, or an object coercible by `fortify()`, or a valid <data.frame>-like object coercible by
  `as.data.frame()`.
Caused by error in `.prevalidate_data_frame_like_object()`:
! `dim(data)` must return an <integer> of length 2.
Run `rlang::last_trace()` to see where the error occurred.
1

There are 1 best solutions below

0
stefan_aus_hannover On

See if this is what you were actually wanting for an output

df_to_plot <- list(list1 = data.frame(list1 = letters[seq(1, 6)],
                                      b = rnorm(n = 6, mean = 7, 1)),
                   list2 = data.frame(list2 = letters[seq(1, 6)], 
                                      b = rnorm(n = 6, mean = 8, 2)),
                   list3 = data.frame(list3 = letters[seq(1, 6)], 
                                      b = rnorm(n = 6, mean = 8, 2)))
col_list <- c('list1', 'list3')

plots <- function(df_list, col_list){
      col <- names(df_list[[col_list]])
       ggplot(df_list[[col_list]], aes(x = as.character(.data[[col[1]]]), 
                          y = as.numeric(.data[['b']]), 
                          fill = as_factor(.data[[col[1]]]))) +
      geom_col()
}

map(col_list, \(var_list) plots(df_to_plot, var_list))

ggplot can't be given a list, it would have to be a dataframe, matrix, ...