R : pass Graph as parameter to a function

前端 未结 2 1907
情话喂你
情话喂你 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条回答
  • 2021-01-28 23:53

    You cannot select a subset of the data within the aesthetics part of a ggplot function, as you are trying to do. However you can achieve this by extracting the original data from the ggplot object, subsetting it and using the subset in the rest of the function.

    r <- ggplot(data=mtcars,aes(x=cyl,y=drat))+geom_point()
    
     graphPoint <- function(graph,point) {
      g <- graph
      data_subset <- g$data[point, ]
      g <- g+geom_point(data = data_subset, 
                        aes(x=cyl,y=drat),pch=1,size=8,col='black')
      g <- g+ geom_point(data = data_subset,
                         aes(x=cyl,y=drat),pch=16,size=5,col='red')
      g
     }
    
     graphPoint(r, point = 2)
    

    PS for upcoming posts I would advise you to make a reproducible example by using data that is generally accessible, like the mtcars data. This would make it easier to help you out.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题