【问题标题】:Make parameterized function to return a function to eval制作参数化函数以将函数返回给 eval
【发布时间】:2016-10-26 19:30:12
【问题描述】:

我想为ggplot2 绘图创建参数化一系列函数以减少冗余。下面我有没有参数化函数的外观(和工作),以及我尝试这样做。

我试图在函数markvline() 中捕获参数值并将其传递给geom_vline()geom_text(),但我想调用markvline()qplot() 函数内联并返回geom_vline() + geom_text()作为参数化,以便它们可以被评估并执行与第一部分中所做的相同的操作。

我认为我需要更好地理解报价/评估/替代,但我现在还没有。对于我将如何构造 markvline() 等效于 geom_vline() + geom_text() 调用并填写参数的任何帮助,我们将不胜感激。

library(ggplot2)

  ## This works
  ## Making labeled vertical lines at 5 and 6
qplot(Sepal.Length, Sepal.Width, data=iris) +
  geom_vline(xintercept=5, color="red", size=1) +
  geom_text(x=5, y=4, label="5", hjust=0) +
  geom_vline(xintercept=6, color="red", size=1) +
  geom_text(x=6, y=4, label="6", hjust=0)


  ## I would like to parameterize these two statements
markvline <- function(e) {
  geom_vline(xintercept=e, color="red", size=1) +
  geom_text(x=e, y=4, label=as.character(e), hjust=0)}

  ## ... but this does not work
qplot(Sepal.Length, Sepal.Width, data=iris) +
  markvline(5) +
  markvline(6)

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我能做的最好的事情是:

    markvline <- function(e) {
      list(geom_vline(xintercept=e, color="red", size=1),
           geom_text(x=e, y=4, label=as.character(e), hjust=0))}
    
    qplot(Sepal.Length, Sepal.Width, data=iris) +
      markvline(5) + markvline(6)
    

    【讨论】:

    • 列表是不错的选择,但不需要单独添加元素,只需qplot(Sepal.Length, Sepal.Width, data=iris) + markvline(5) +markvline(6)
    • 谢谢!这告诉我的一件事(以及从我的示例返回的一些错误代码)是我可以返回评估后的各个函数(为您将其返回到列表中),但我不能 combine 在我的函数中使用+。这暗示geom_vline()geom_text() 不会以某种方式与+ 单独结合,但需要折叠到qplot() 返回的任何对象中。这是一个很好的线索!
    • 谢谢。这比我想象的要容易。我会编辑我的答案
    • 此解决方案有效,因此被接受,谢谢。现在要弄清楚为什么会这样。我也欢迎任何为此目的的 cmets。
    • 到目前为止,我最好的猜测是 qplot 对象属于 ggggplot 类。 geom_* 对象的类是 LayerInstanceLayerggproto。重载的+ 运算符从左到右关联,并且可能定义为添加gg 对象和LayerInstance 对象以产生gg 对象。但它没有定义为添加两个LayerInstance 对象。但是,+ 是为将LayerInstance 对象列表添加到gg 对象而定义的。
    猜你喜欢
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多