I am trying to understand how to use walk
to silently (without printing to the console) return ggplot2
plots in a pipeline.
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))
I was expecting example #2 to work, but I must be missing or not understanding something. I want the plots from #1 without the console output.
I'm not sure why it works with base R plot
in your 4th example honestly. But for ggplot
, you need to explicitly tell walk
that you want it to print. Or as the comments suggest, walk
will return plots (I misspoke in my first comment on that) but not print them. So you could use walk
to save the plots, then write a second statement to print them. Or do it in one walk
call.
Two things here: I'm using function notation inside walk
, instead of purrr
's abbreviated ~
notation, just to make it clearer what's going on. I also changed the 10 to 4, just so I'm not flooding everyone's screens with tons of plots.
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)
})




Created on 2018-05-09 by the reprex package (v0.2.0).
This should work
10 %>%
rerun(x = rnorm(5), y = rnorm(5)) %>%
map(~ data.frame(.x)) %>%
map(function(x) {
ggplot(x, aes(x, y)) + geom_point()
})
来源:https://stackoverflow.com/questions/50257080/how-to-use-walk-to-silently-plot-ggplot2-output-with-purrr