簡體   English   中英

將dplyr SE與ggplot2一起使用

[英]Use dplyr SE with ggplot2

我經常在包裝函數中結合使用dplyrggplot2進行分析。 當我使用tidyeval遷移到v.0.7.1的新NSE / SE范例時,我正在努力使這種組合起作用。 我發現ggplot無法理解未引用的Quers(尚未)。 以下內容不起作用:

example_func <- function(col) {
  col <- enquo(col)
  mtcars %>% count(!!col) %>% 
    ggplot(aes((!!col), n)) +
    geom_bar(stat = "identity")
}
example_func(cyl)
# Error in !col : invalid argument type

我目前使用以下解決方法。 但是我認為必須有更好的方法。

example_func2 <- function(col) {
  col <- enquo(col)
  mtcars %>% count(!!col) %>% 
    ggplot(aes_string(rlang::quo_text(col), "n")) +
    geom_bar(stat = "identity")
}

請告訴我結合這兩種的最佳方法。 謝謝!

對此似乎有兩種思考方式。

方法1:分離關注點。

我希望我的繪圖工作與爭吵的工作完全分開。 另外,您可以為組命名,這似乎是解決問題的最簡單方法[盡管您確實松開了原始的列名]。 因此,解決您要嘗試做的事情的一種方法可以是通過:

library(tidyverse)

concern1_data <- function(df, col) {
  group <- enquo(col)
  df %>% 
    group_by(group = !!group) %>% 
    summarise(n = n())
}

concern2_plotting <- function(df){
  ggplot(data=df) +
    geom_bar(aes(group, n), stat = "identity")
}

mtcars %>% 
  concern1_data(am) %>% 
  concern2_plotting()

這可以實現您嘗試或多或少要做的事情,並使關注點分開(值得一提)。

方法2:接受並等待

事情是:ggplot2中尚未實現tidyeval。 - 來自鏈接的 Colin Fay

我認為這是ggplot2目前不支持的功能,但我無法想象ggplot2無法獲得此功能。 還沒有呢。

如果已經在處理quasure,則使用aes_會更容易,后者接受以公式引用的輸入: aes_(col, ~n)

這段代碼解決了您的問題:

library(tidyverse)
example_func <- function(col) {
  col <- enquo(col)
  mtcars %>% count(!!col) %>% 
    ggplot(aes_(col, ~n)) +
    geom_bar(stat = "identity")
}

example_func(cyl)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM