【问题标题】:Ability to specify ggplot aesthetics to function that should return a ggplot object能够指定应该返回 ggplot 对象的 ggplot 美学功能
【发布时间】:2015-04-22 02:28:06
【问题描述】:

我正在尝试构建一个行为类似于 ggplot 函数的函数,并且还返回一个 ggplot 对象,其他函数可以进一步处理(添加方面、应用主题等)。

我现在面临的障碍是我无法让传递给函数的参数像我期望的那样工作。

data(iris)
te <- function(data,x,y){

  g <- ggplot(data,aes_q(x=quote(x),y=quote(y))) + scale_x_continuous() + 
  scale_y_continuous() + geom_point()
  return(g)

}
te(iris,x=Species,y=Petal.Length)

然后我得到的是:

Error: geom_point requires the following missing aesthetics: x, y

我希望这将使我能够传递参数而不是字符串,但显然我在这里做错了。对我来说,奇怪的是 geom_point 是抱怨的函数。怎么会?

【问题讨论】:

    标签: r function ggplot2 aesthetics


    【解决方案1】:

    在函数内部你需要使用substitute 而不是quote

    data(iris)
    te <- function(data,x,y){
      
      x <- substitute(x)
      y <- substitute(y)
      g <- ggplot(data,aes_q(x=x,y=y)) + scale_x_discrete() + 
        scale_y_continuous() + geom_point()
      return(g)
      
    }
    te(iris,x=Species,y=Petal.Length)
    

    这会很完美。

    附:我将 scale_x_continuous 更改为 scale_x_discrete 因为 Species 是离散的

    【讨论】:

      【解决方案2】:

      调用函数时尝试quote

      data(iris)
      library(ggplot2)
      te <- function(data,x,y){
        g <- ggplot(data,aes_q(x,y)) + scale_x_continuous() + 
          scale_y_continuous() + geom_point()
        return(g)
      
      }
      te(iris,x=quote(Species),y=quote(Petal.Length))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-16
        • 1970-01-01
        • 1970-01-01
        • 2012-11-29
        • 2014-05-09
        相关资源
        最近更新 更多