R : pass Graph as parameter to a function

前端 未结 2 1941
情话喂你
情话喂你 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.

提交回复
热议问题