【问题标题】:Mix dots and named arguments in function calling aes for ggplot2在 ggplot2 调用 aes 的函数中混合点和命名参数
【发布时间】:2017-07-31 16:16:14
【问题描述】:

我正在尝试围绕 ggplot 创建一个包装器,它允许我添加一些美学,例如 x 变量或颜色,但始终预填充 yyminymax,而无需使用带引号的变量名字。

由于 ggplot2 无法使用 tidy 评估,我必须为此使用 NSE,但我被卡住了,我可以找到 herehere 的信息并检查一些功能让我尝试像 unlist(...) 和使用 @ 987654329@。但它们只会抛出不同的错误。

在下面的函数中,我基本上希望能够调用ci_plot() 或例如ci_plot(color = cyl)

library(dplyr)
library(ggplot2)
library(purrr)
library(tidyr)


ci_plot <- function(data, ...) {
  ggplot(data, aes(..., y = y, ymin = ymin, ymax = ymax))  
}

mpg %>%
  group_by(manufacturer) %>%
  nest() %>%
  mutate(x = map(data, ~mean_se(.x$hwy))) %>%
  unnest(x) %>%
  ci_plot() + 
  geom_pointrange()

【问题讨论】:

标签: r ggplot2 nse


【解决方案1】:

您有几个选项,具体取决于您希望用户如何将变量传递给函数。

使用字符串和aes_string

您可以让用户通过字符串提供变量。在这种情况下,您需要 aes_string 中的 ...,然后为“固定”变量添加单独的 aes 层。

你的数据操作代码为我返回了所有NA,所以这个例子更简单。我将y 变量固定为cty

ci_plot = function(data, ...) {
     ggplot(data, aes_string(...) )  +
          aes( y = cty )
}

ci_plot(data = mpg, x = "displ", color = "class") +
     geom_point()

使用波浪号和aes_

另一种方法是让用户在使用函数时对变量使用波浪号。在这种情况下,aes_ 既可用于固定变量也可用于可变变量。

ci_plot2 = function(data, ...) {
     ggplot(data, aes_(..., y = ~cty ) ) 
}

ci_plot2(data = mpg, x = ~displ, color = ~class) +
     geom_point()

两个函数的结果图:

【讨论】:

  • 感谢您的详尽回复。但是我一直在寻找方法来保持语法与其他香草 ggplot2 函数相同,不带引号(我可能没有足够强调它)。如果您有兴趣,我现在设法解决了这个问题并发布了答案。
【解决方案2】:

经过更多挖掘后,我找到了影子的答案here,并想出了如何根据我的目的调整它。 我会尽量概述解决方案。

ci_plot <- function(data, ...) {
  # Create a list of unevaluated parameters,
  # removing the first two, which are the function itself and data.
  arglist <- as.list(match.call()[-c(1,2)]) 

  # We can add additional parameters to the list using substitute
  arglist$ymin = substitute(ymin)
  arglist$y    = substitute(y)
  arglist$ymax = substitute(ymax)

  # I suppose this allows ggplot2 to recognize that it needs to quote the arguments
  myaes <- structure(arglist, class="uneval")

  # And this quotes the arguments?
  myaes <- ggplot2:::rename_aes(myaes)

  ggplot(data, myaes)  
}

那个函数让我可以这样写代码

mpg %>%
  group_by(manufacturer, cyl) %>%
  nest() %>%
  mutate(x = map(data, ~mean_se(.x$hwy))) %>%
  unnest(x) %>%
  ci_plot(x = cyl, color = manufacturer) + 
  geom_pointrange()

【讨论】:

    猜你喜欢
    • 2016-07-26
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 2017-11-25
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多