【问题标题】:Control which aestheic to use in ggplot2 function控制在 ggplot2 函数中使用哪种美学
【发布时间】:2017-01-27 02:23:21
【问题描述】:

我想做一系列的例子并尝试使用一个函数。如何控制是否使用形状、alpha、大小等?这是我正在使用的代码:

library(ggplot2)

ggplot_example <- 
  function(aesthetic, var){  
    ggplot(mpg) +
    geom_point(aes(x = displ, y = hwy, 
                   aesthetic = get(var)))
  }

ggplot_example("color", "hwy")
ggplot_example("color", "class")
ggplot_example("alpha", "cty")
ggplot_example("size", "cty")

现在get(aesthetic) = get(var) 正在引发错误,当我只使用aesthetic = get(var) 时,它会忽略aesthetic 参数。

【问题讨论】:

    标签: r function ggplot2


    【解决方案1】:

    您可能应该阅读metaprogramming in Advanced R。您不能将变量粘贴在任何地方。您需要小心识别函数是否需要字符串、符号或表达式,并且需要能够从另一个中生成一个。

    使函数工作的最简单方法可能是使用do.call() 动态构建aes() 调用,同时使用setNames() 设置参数名称。试试这个

    ggplot_example <- 
      function(aesthetic, var){  
        ggplot(mpg) +
        geom_point(do.call("aes", setNames(list(quote(displ), quote(hwy), 
                       as.name(var)), c("x", "y", aesthetic))))
      }
    
    ggplot_example("color", "hwy")
    ggplot_example("color", "class")
    ggplot_example("alpha", "cty")
    ggplot_example("size", "cty")
    

    【讨论】:

    • 哦,哇,我还有很多东西要学。找它的时候我离得很近。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多