在 ggplot2 中使用 pmap 自动绘制不同数据集的图形

Using pmap in ggplot2 to automate plotting graphs of different datasets

我正在尝试通过编写一个函数来自动化我的条形图,该函数将采用不同的数据集以及 x 和 y 轴值。

由于该函数具有三个参数(数据集、x 轴和 y 轴),我正在使用 purrr 中的 pmap()。

当我删除数据集参数并使用 map2() 而不是 pmap() 时,该函数工作正常

这是我写的代码:

forest_day <- forest %>% group_by(day) %>% summarise(n())%>%rename(count1 = `n()`)
forest_month <- forest %>% group_by(month) %>% summarise(n())%>%rename(count1 = `n()`)

pbar <- function(data, x, y) {
  ggplot(data = data) + aes_string(x = x, y = y) + geom_bar(stat = 'identity')
}

l1 <- list(forest_month, forest_month$month, forest_month$count1)
pmap(l1, pbar)
l2 <- list(forest_day, forest_day$day, forest_day$count1)
pmap(l2,pbar)

我在使用 pmap() 时得到的错误代码是这样的:

"Element 1 of .l must have length 1 or 12, not 2"

在此先感谢您的帮助!

由于我没有你的数据,我使用 mtcarsiris 生成了我自己的数据集。在您的 ggplot 调用中使用 get(data) 应该可以解决您的问题。请注意,您需要以字符串形式提供所有参数。在您自己的示例中,您已经使用 aes_string 因此 xy 应该作为字符串提供。使用 get 将字符串作为参数并在全局环境中查找对象。

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

mtcars_cyl <- mtcars %>% group_by(cyl) %>% summarise(count1 = n())
iris_Species <- iris %>% group_by(Species) %>% summarise(count1 = n())

pbar <- function(data, x, y) {
  ggplot(data = get(data), aes_string(x = x, y = y)) + geom_bar(stat = 'identity')
}

l1 <- list("mtcars_cyl","cyl", "count1")
pmap(l1, pbar)
map2("cyl", "count1" )
l2 <- list("iris_Species", "Species", "count1")
pmap(l2,pbar)

如果你总是使用相同的 y-variable count1。然后就可以使用map2了。这是您有两个列表的示例。一个列表 ls_data 提供要循环的数据帧,另一个列表 ls_x 提供 x-argument 到 ggplot2count1 然后在 map2 内的 lambda 函数中定义。调用 map2 会同时生成两个图。或者 walk2 将在不向控制台打印 [[1]] [[2]] 的情况下生成绘图。

ls_data <- list("mtcars_cyl","iris_Species")
ls_x <- list("cyl","Species")

map2(ls_data, ls_x, ~ pbar(.x, .y, "count1"))
walk2(ls_data, ls_x, ~ pbar(.x, .y, "count1"))

调用 map2 的另一种方法是将两个参数都放在命名列表中,数据集的名称作为列表名称,x-argument 作为列表输入。

args <- c(mtcars_cyl = "cyl",
          iris_Species = "Species")

map2(names(args), args, ~ pbar(.x, .y, "count1"))

祝你数据顺利。