【问题标题】:Programming with ggplot2 and dplyr使用 ggplot2 和 dplyr 进行编程
【发布时间】:2023-03-08 13:15:01
【问题描述】:

我想使用管道将dplyrggplot 组合在一个函数中,并且现在正在努力解决一些问题。

这是第一个简单的工作。采用数据框并按指定列和值过滤的函数。

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

现在我正在尝试直接通过管道传递给 ggplot 函数...报错

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]], ...) 中:重新启动中断的 Promise 评估

最后一个。如何添加分面?

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 来解决。 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

【问题讨论】:

    标签: r function ggplot2 dplyr


    【解决方案1】:

    @Tung 的答案可以使用{{ 语法进行简化。 https://rlang.r-lib.org/reference/quasiquotation.html

    library(rlang)
    library(dplyr)
    library(ggplot2)
    
    foo <- function(df, y, gr, t = 4) {
      df %>% 
        filter({{ y }}> t) %>% 
        ggplot(aes({{ y }})) + 
        geom_histogram() +  
        facet_grid(cols = vars({{ gr }}))
    }
    
    foo(mtcars, y = cyl, gr = vs)
    

    【讨论】:

      【解决方案2】:

      2018年7月发布的ggplot2 v3.0.0支持!!(砰砰)、!!!:=

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

      所以你的例子可以修改如下:

      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 package (v0.2.0) 于 2018 年 4 月 4 日创建。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-17
        • 2013-10-01
        • 2014-02-23
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 2017-10-15
        • 2018-06-09
        相关资源
        最近更新 更多