用ggplot2和dplyr编程 [英] Programming with ggplot2 and dplyr

查看:135
本文介绍了用ggplot2和dplyr编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用管道将dplyrggplot组合在一个函数中,并且现在遇到了一些问题.

I want to combine dplyr and ggplot within one function using piping and struggling with some issues now.

这是第一个正在工作的简单工具.该函数采用数据框并按指定的列和值进行过滤.

Here is the first easy one which is working. Function which takes a dataframe and filters by a specified column and value.

foo <- function(df, y, t = 4){
  tmp <- df %>% 
          filter(!!enquo(y) > t)
  ggplot(tmp, aes_(substitute(y))) + 
      geom_histogram()  
}
foo(mtcars, cyl)

现在我正尝试直接通过管道传输到ggplot函数...出现错误

Now I'm trying to pipe directly to the ggplot function...gives an error

foo <- function(df, y, t=4){
  df %>% 
     filter(!!enquo(y) > t) %>% 
        ggplot(aes_(substitute(y))) + 
            geom_histogram()  
}
foo(mtcars, cyl)

FUN(X [[i]],...)中的错误:找不到对象'cyl' 另外:警告消息: 在FUN(X [[i]],...)中:重新开始中断的承诺评估

Error in FUN(X[[i]], ...) : object 'cyl' not found In addition: Warning message: In FUN(X[[i]], ...) : restarting interrupted promise evaluation

和最后一个.如何添加构面?

and the last one. How to add a facet?

foo <- function(df, y, gr, t=4){
  df %>% 
       filter(!!enquo(y) > t) %>% 
  ggplot(aes_(substitute(y))) + 
      geom_histogram() +  
      facet_grid(~gr)
}
foo(mtcars, y= cyl, gr= vs)

编辑

第二个问题可以使用aes_q代替aes_& substitute. 来源

Edit

The second issue can be solved using aes_q instead of aes_ & substitute. Source

foo <- function(df, y, gr, t=4){
  y <- enquo(y)
  df %>% 
    filter(!!y > t) %>% 
       ggplot(aes_q(y)) + 
           geom_histogram()
}
foo(mtcars, cyl)

使用ggplot2_2.2.1

推荐答案

facet_wrap()facet_grid()支持vars()输入. facet_grid()的前两个参数变为rowscols. facet_grid(vars(cyl), vars(am, vs))等同于facet_grid(cyl ~ am + vs)facet_grid(cols = vars(am, vs))等同于facet_grid(. ~ am + vs).

facet_wrap() and facet_grid() support vars() inputs. The first two arguments of facet_grid() become rows and cols. facet_grid(vars(cyl), vars(am, vs)) is equivalent to facet_grid(cyl ~ am + vs) and facet_grid(cols = vars(am, vs)) is equivalent to facet_grid(. ~ am + vs).

因此您的示例可以如下修改:

So your example can be modified as follow:

library(rlang)
library(tidyverse)

foo <- function(df, y, gr, t=4) {
  y <- enquo(y)
  gr <- enquo(gr)

  df %>% 
    filter(!!y > t) %>% 
    ggplot(aes(!!y)) + 
    geom_histogram() +  
    facet_grid(cols = vars(!!gr))
}

foo(mtcars, y= cyl, gr= vs)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

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

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

这篇关于用ggplot2和dplyr编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆