How to use walk to silently plot ggplot2 output with purrr

前端 未结 2 1321
再見小時候
再見小時候 2021-01-11 15:51

I am trying to understand how to use walk to silently (without printing to the console) return ggplot2 plots in a pipeline.

library         


        
2条回答
  •  清酒与你
    2021-01-11 15:58

    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).

提交回复
热议问题