ggplot2:使用 purrr::map() 从数据帧列表中创建绘图列表

问题描述 投票:0回答:0

有以下 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)))

我起诉一个字符串列表来识别我想要绘制的数据帧

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

现在我创建了一个函数来绘制绘图并使用

map()
循环遍历列表并返回绘图列表

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

但是我收到以下错误

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.
r ggplot2 purrr
© www.soinside.com 2019 - 2024. All rights reserved.