【发布时间】:2018-10-19 18:58:36
【问题描述】:
我试图了解如何使用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))
我期待示例 #2 能够正常工作,但我一定是遗漏或不理解某些内容。我想要 #1 中没有控制台输出的图。
【问题讨论】:
-
walk不会返回或打印任何内容,因此如果要打印绘图,则需要明确说明。您可以将ggplot语句包装在print调用中 -
@camille - 啊,谢谢,请随时回答 - 但是,仍然有点困惑 - 添加了适用于基础绘图的示例 #4。
-
walk不可见地返回其输入。使用您的 EX2,如果您运行p = 10 %>% rerun(x = rnorm(5), y = rnorm(5)) %>% map(~ data.frame(.x)) %>% walk(~ ggplot(., aes(x, y)) + geom_point()),然后键入p,您将看到p包含数据帧的输入列表。 -
EX1 不会将单个图或列表元素编号打印到控制台,如果您将其通过管道传输到其他内容。例如,
library(gridExtra); 10 %>% rerun(x = rnorm(5), y = rnorm(5)) %>% map(~ data.frame(.x)) %>% map(~ ggplot(., aes(x, y)) + geom_point()) %>% grid.arrange(grobs=., ncol=5)。或者,只需调用一次 map:10 %>% rerun(x = rnorm(5), y = rnorm(5)) %>% map(~ data.frame(.x) %>% ggplot(aes(x, y)) + geom_point()) %>% grid.arrange(grobs=., ncol=5).