0

我正在尝试围绕它创建一个包装器,ggplot它允许我添加一些美学,如 x 变量或颜色,但总是 prefills yyminymax不必使用带引号的变量名。

由于 ggplot2 不能使用 tidy 评估,我必须为此使用 NSE,但我被卡住了,我可以在这里这里找到的信息并检查一些功能让我尝试unlist(...)使用match.call(). 但他们只会抛出不同的错误。

在下面的函数中,我基本上希望能够调用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()
4

2 回答 2

2

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

使用字符串和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()

两个函数的结果图: 在此处输入图像描述

于 2017-07-31T20:45:51.723 回答
0

经过更多挖掘后,我在这里找到了影子的答案,并想出了如何根据我的目的对其进行调整。我将尽我所能概述解决方案。

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()
于 2017-08-01T10:00:30.817 回答