R : pass Graph as parameter to a function

前端 未结 2 1931
情话喂你
情话喂你 2021-01-28 23:24

I have a decent looking graph ,which I plotted using

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

Now i want to h

2条回答
  •  萌比男神i
    2021-01-29 00:00

    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)
    

    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).

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

提交回复
热议问题