2017-07-31 78 views
0

我试图创建ggplot周围的包装,让我增加一些美感,如x变量或颜色,但总是prefills yyminymax不必工作带有引用的变量名称。混合点和命名参数的函数调用的AES GGPLOT2

由于GGPLOT2不能用整洁的评价我都用NSE在这一点,但我坚持,信息我能找到herehere和检查的一些功能让我尝试之类的东西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() 
+0

这可能帮助代码:https://stackoverflow.com/questions/15458526/r-pass-variable-column-indices-to -ggplot2 – Wave

回答

0

后一些更多的挖我找到影子的答案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() 
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() 

所得到的来自这两个函数的情节: enter image description here

+0

感谢您的彻底回复。然而,我正在寻找方法来保持语法与其他香草ggplot2函数相同,没有引号(我可能没有足够强调)。我现在设法解决了这个问题,并且如果您有兴趣发布了答案。 –

相关问题