R : 将 Graph 作为参数传递给函数 [英] R : pass Graph as parameter to a function

查看:56
本文介绍了R : 将 Graph 作为参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来不错的图表,我用它绘制了

I have a decent looking graph ,which I plotted using

r <- ggplot(data=data2.Gurgaon,aes(x=createdDate,y=count))+geom_point()

现在我想突出图中的几个点,比如 500,1000,5000 等等.所以,我正在尝试编写一个函数,在该函数中我可以传递我想要标记的点下面是我写的函数

Now i want to higlight few points on the graph say 500,1000,5000 etc.. so ,I am trying to write a function , in which i can pass point I want to mark Below is the function I have written

graphPoint <- function(graph,point) {
  g <- graph
  g <- g+geom_point(aes(x=createdDate[point],y=count[point]),pch=1,size=8,col='black')
  g <- g+ geom_point(aes(x=createdDate[point],y=count[point]),pch=16,size=5,col='red')
  g
}

当我传递参数时

r -> graphPoint(r,500)

这是错误的

Error in lapply(X = x, FUN = "[", ..., drop = drop) : 
  object 'point' not found

我对 R 不太好.希望它可能,但我在某个小点上失踪了..谢谢.

i am not that great with R . Hope its possible , But I am missing at some small point .. Thanks.

推荐答案

这实际上是 ggplot 中一个极其微妙(并且令人讨厌...)的问题,尽管不是错误.aes(...) 函数首先在默认数据集的上下文中评估所有符号(例如,它查找具有该名称的列),如果在全局环境中失败/em>.它不会像您所期望的那样在调用链上向上移动.因此,在您的情况下,符号 point 首先在 data2.Gurgaon 的上下文中进行评估.由于没有这样的列,它在全局环境中查找 point,但 不是 在您的 graphPoint(...) 的上下文中功能.这是一个演示:

This is actually an extremely subtle (and annoying...) problem in ggplot, although not a bug. The aes(...) function evaluates all symbols first in the context of the default dataset (e.g. it looks for columns with that name), and, if that fails in the global environment. It does not move up the calling chain, as you might justifiably expect it to. So in your case the symbol point is first evaluated in the context of data2.Gurgaon. Since there is no such column, it looks for point in the global environment, but not in the context of your graphPoint(...) function. Here is a demonstration:

df <- mtcars
library(ggplot2)
graphPoint <- function(graph,point) {
  g <- graph
  g <- g + geom_point(aes(x=wt[point],y=mpg[point]),pch=1,size=8,col='black')
  g <- g + geom_point(aes(x=wt[point],y=mpg[point]),pch=16,size=5,col='red')
  g
}

ggp <- ggplot(df, aes(x=wt, y=mpg)) + geom_point()
point=10
graphPoint(ggp, 10)

之所以有效,是因为我在全局环境中定义了point;函数内的 point 变量被忽略(您可以通过使用 10 以外的其他值调用 fn 来证明这一点:您将获得相同的图).

The reason this works is because I defined point in the global environment; the point variable inside the function is being ignored (you can demonstrate that by calling the fn with something other than 10: you'll get the same plot).

解决此问题的正确方法是将 data=... 参数设置为子集,如另一个答案所示.

The correct way around this is by subsetting the data=... argument, as shown in the other answer.

这篇关于R : 将 Graph 作为参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆