當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R ggplot2 vars 引用分麵變量


就像 aes() 一樣,vars()quoting function,它在數據集的上下文中接受要評估的輸入。這些輸入可以是:

  • 變量名

  • 複雜的表達

在這兩種情況下,結果(變量表示的向量或表達式的結果)都用於生成分麵組。

用法

vars(...)

參數

...

< data-masking > 自動引用變量或表達式。這些在數據上下文中進行評估以形成分麵組。可以命名(名稱傳遞給 labeller )。

也可以看看

例子

p <- ggplot(mtcars, aes(wt, disp)) + geom_point()
p + facet_wrap(vars(vs, am))


# vars() makes it easy to pass variables from wrapper functions:
wrap_by <- function(...) {
  facet_wrap(vars(...), labeller = label_both)
}
p + wrap_by(vs)

p + wrap_by(vs, am)


# You can also supply expressions to vars(). In this case it's often a
# good idea to supply a name as well:
p + wrap_by(drat = cut_number(drat, 3))


# Let's create another function for cutting and wrapping a
# variable. This time it will take a named argument instead of dots,
# so we'll have to use the "enquote and unquote" pattern:
wrap_cut <- function(var, n = 3) {
  # Let's enquote the named argument `var` to make it auto-quoting:
  var <- enquo(var)

  # `as_label()` will create a nice default name:
  nm <- as_label(var)

  # Now let's unquote everything at the right place. Note that we also
  # unquote `n` just in case the data frame has a column named
  # `n`. The latter would have precedence over our local variable
  # because the data is always masking the environment.
  wrap_by(!!nm := cut_number(!!var, !!n))
}

# Thanks to tidy eval idioms we now have another useful wrapper:
p + wrap_cut(drat)

源代碼:R/facet-.R

相關用法


注:本文由純淨天空篩選整理自Hadley Wickham等大神的英文原創作品 Quote faceting variables。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。