当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。