如何使用walk以静默方式使用purrr绘制ggplot2输出

Jas*_*lns 9 r ggplot2 purrr

我试图了解如何使用walk静默(不打印到控制台)返回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))
Run Code Online (Sandbox Code Playgroud)

我期待着#2的例子可以工作,但我必须缺少或不理解某些东西.我想要#1没有控制台输出的情节.

cam*_*lle 10

我不确定为什么它plot在你的第四个例子中诚实地与基础R一起使用.但是ggplot,您需要明确告诉walk您要打印它.或者正如评论所示,walk将返回情节(我在第一次评论时错过了)但不打印它们.所以你可以使用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)
    })
Run Code Online (Sandbox Code Playgroud)

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

  • 不直接相关,但由于有些人可能会犯与我相同的错误,请注意,无法将 `%&gt;% print` 语句通过管道传输到您的 `ggplot` 链,因为由于运算符优先级,它只会打印链(此处为“geom_point”)。因此,必须以“print(”开始整个链,或者使用一个额外的行,就像这个答案一样。 (2认同)