Programming with ggplot2 and dplyr

后端 未结 2 1133
-上瘾入骨i
-上瘾入骨i 2021-01-01 06:32

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

2条回答
  •  情歌与酒
    2021-01-01 07:11

    ggplot2 v3.0.0 released in July 2018 supports !! (bang bang), !!!, and :=.

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

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

提交回复
热议问题