如何使用 walk 静默绘制带有 purrr 的 ggplot2 输出

How to use walk to silently plot ggplot2 output with purrr

我正在尝试了解如何使用 walk 静默地(不打印到控制台)return ggplot2 管道中的绘图。

library(tidyverse)

# EX1: This works, but prints [[1]], [[2]], ..., [[10]] to the console
10 %>%
  rerun(x = rnorm(5), y = rnorm(5)) %>%
  map(~ data.frame(.x)) %>%
  map(~ ggplot(., aes(x, y)) + geom_point())

# EX2: This does not plot nor print anything to the console
10 %>%
  rerun(x = rnorm(5), y = rnorm(5)) %>%
  map(~ data.frame(.x)) %>%
  walk(~ ggplot(., aes(x, y)) + geom_point())

# EX3: This errors: Error in obj_desc(x) : object 'x' not found
10 %>%
  rerun(x = rnorm(5), y = rnorm(5)) %>%
  map(~ data.frame(.x)) %>%
  pwalk(~ ggplot(.x, aes(.x$x, .x$y)) + geom_point())

# EX4: This works with base plotting
10 %>%
  rerun(x = rnorm(5), y = rnorm(5)) %>%
  map(~ data.frame(.x)) %>%
  walk(~ plot(.x$x, .x$y))

我原以为示例 #2 会起作用,但我一定是遗漏了或不理解某些东西。我想要 #1 中没有控制台输出的图。

这应该有效

10 %>%
  rerun(x = rnorm(5), y = rnorm(5)) %>%
  map(~ data.frame(.x)) %>%
  map(function(x) {
      ggplot(x, aes(x, y)) + geom_point()
  })

老实说,我不确定为什么它与第 4 个示例中的基数 R plot 一起使用。但是对于 ggplot,您需要明确告诉 walk 您希望它打印。或者正如评论所暗示的那样,walk 将 return 绘图(我在第一条评论中说错了)但不会打印它们。因此,您可以使用 walk 来保存绘图,然后编写第二条语句来打印它们。或者在一个 walk 电话中完成。

这里有两点:我在 walk 中使用函数符号,而不是 purrr 的缩写 ~ 符号,只是为了更清楚地说明发生了什么。我还将 10 更改为 4,这样我就不会在每个人的屏幕上充斥大量情节。

library(tidyverse)

4 %>%
    rerun(x = rnorm(5), y = rnorm(5)) %>%
    map(~ data.frame(.x)) %>%
    walk(function(df) {
        p <- ggplot(df, aes(x = x, y = y)) + geom_point()
        print(p)
    })

reprex package (v0.2.0) 创建于 2018-05-09。