为了账号安全,请及时绑定邮箱和手机立即绑定

在R中的另一个函数中使用ggplot()

在R中的另一个函数中使用ggplot()

呼如林 2019-09-21 14:53:33
我正在尝试使用ggplot2库编写一个简单的绘图函数。但是调用ggplot找不到函数参数。考虑一个data.frame调用means,它存储了两个要绘制的条件和两个平均值(条件将出现在X轴上,均值出现在Y轴上)。library(ggplot2)m <- c(13.8, 14.8)cond <- c(1, 2)means <- data.frame(means=m, condition=cond)means# The output should be:#     means    condition#   1 13.8     1#   2 14.8     2testplot <- function(meansdf){  p <- ggplot(meansdf, aes(fill=meansdf$condition, y=meansdf$means, x = meansdf$condition))  p + geom_bar(position="dodge", stat="identity")}testplot(means)# This will output the following error:# Error in eval(expr, envir, enclos) : object 'meansdf' not found所以似乎ggplot正在调用eval,找不到参数meansdf。有谁知道我如何成功地将函数参数传递给ggplot?(注意:是的,我可以直接调用ggplot函数,但是最后我希望使我的plot函数做更复杂的事情!:))
查看完整描述

3 回答

?
达令说

TA贡献1821条经验 获得超6个赞

正如Joris和Chase已经正确回答的那样,标准的最佳实践是简单地省略meansdf$零件并直接引用数据框列。


testplot <- function(meansdf)

{

  p <- ggplot(meansdf, 

              aes(fill = condition,

                  y = means,

                  x = condition))

  p + geom_bar(position = "dodge", stat = "identity")

}

之所以可行,是因为aes在全局环境中或在传递给的数据帧中寻找引用的变量ggplot。这也是为什么你的示例代码-使用meansdf$condition等-不工作:meansdf在全球环境既不可用,也不是可以传递到数据帧里面ggplot,这是meansdf本身。


在全局环境中而不是在调用环境中寻找变量的事实实际上是ggplot2中的一个已知错误,Hadley目前认为该错误不可修复。如果希望使用局部变量(例如scale)来影响用于绘图的数据,则会导致问题:


testplot <- function(meansdf)

{

  scale <- 0.5

  p <- ggplot(meansdf, 

              aes(fill = condition,

                  y = means * scale,   # does not work, since scale is not found

                  x = condition))

  p + geom_bar(position = "dodge", stat = "identity")

}

Winston Chang在引用的GitHub问题中提供了一种很好的解决方法:environment在调用时,将参数显式设置为当前环境ggplot。上面的示例如下所示:


testplot <- function(meansdf)

{

  scale <- 0.5

  p <- ggplot(meansdf, 

              aes(fill = condition,

                  y = means * scale,

                  x = condition),

              environment = environment())   # This is the only line changed / added

  p + geom_bar(position = "dodge", stat = "identity")

}


## Now, the following works

testplot(means)


查看完整回答
反对 回复 2019-09-21
?
慕哥6287543

TA贡献1831条经验 获得超10个赞

这是一个简单的技巧,我在函数环境(第二行)中经常使用它来定义变量:


FUN <- function(fun.data, fun.y) {

    fun.data$fun.y <- fun.data[, fun.y]

    ggplot(fun.data, aes(x, fun.y)) + 

        geom_point() + 

        scale_y_continuous(fun.y)    

}


datas <- data.frame(x = rnorm(100, 0, 1),

                    y = x + rnorm(100, 2, 2),

                    z = x + rnorm(100, 5, 10))

FUN(datas, "y")

FUN(datas, "z")

请注意,当使用不同的变量或数据集时,y轴标签也会如何变化。


查看完整回答
反对 回复 2019-09-21
  • 3 回答
  • 0 关注
  • 1042 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信