将标题添加到使用 map() 创建的 ggplots

Add titles to ggplots created with map()

将标题添加到我在下面使用 map 函数创建的每个 ggplot 的最简单方法是什么?我希望标题反映每个数据框的名称 - 即 4、6、8(圆柱体)。

谢谢:)

mtcars_split <- 
  mtcars %>%
  split(mtcars$cyl)

plots <-
  mtcars_split %>%
  map(~ ggplot(data=.,mapping = aes(y=mpg,x=wt)) + 
        geom_jitter() 
  # + ggtitle(....))

plots

map2names 结合使用。

plots <- map2(
  mtcars_split,
  names(mtcars_split),
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y)
)

编辑:alistaire 指出这与 imap

相同
plots <- imap(
  mtcars_split,
  ~ggplot(data = .x, mapping = aes(y = mpg, x = wt)) + 
    geom_jitter() +
    ggtitle(.y)
)

也许您有兴趣改用 facet_wrap

ggplot(mtcars, aes(y=mpg, x=wt)) + geom_jitter() + facet_wrap(~cyl)

您可以使用 purrr::map2():

mtcars_split <- mtcars %>% split(mtcars$cyl)

plots <- map2(mtcars_split, titles, 
  ~ ggplot(data=.x, aes(mpg,wt)) + geom_jitter() + ggtitle(.y)
)

编辑

抱歉与 Paul 的 回答重复。