How to use walk to silently plot ggplot2 output with purrr

巧了我就是萌 提交于 2019-12-01 01:09:15

问题


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.


回答1:


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




回答2:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!