本文介绍了如何使用walk通过purrr静默绘制ggplot2输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图了解如何使用walk静默(不打印到控制台)在管道中返回ggplot2绘图.

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

我希望示例#2能够正常工作,但是我必须丢失或不了解某些内容.我想要没有控制台输出的#1地块.

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.

推荐答案

我不确定在第四个示例中它为什么能与基数R plot一起使用.但是对于ggplot,您需要明确告诉walk您要打印它.或如注释所建议的那样,walk将返回图(我在第一个注释中打错了点),但不打印它们.因此,您可以使用walk保存曲线图,然后编写第二条语句以打印曲线图.或者在一个walk呼叫中完成.

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.

这里有两件事:我在walk内使用函数符号,而不是purrr的缩写~符号,只是为了更清楚地说明正在发生的事情.我也将10更改为4,只是为了避免在每个人的屏幕上堆满很多积.

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

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

Created on 2018-05-09 by the reprex package (v0.2.0).

这篇关于如何使用walk通过purrr静默绘制ggplot2输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 14:54