Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using gglocator() within another function

I’m trying to use gglocator() within a function that looks like this:

my_function<- function(point_num) {

 x11()

 iris %>% 
   ggplot()+
     aes(Sepal.Width,Sepal.Length)+
     geom_point()

 points <- gglocator(n = point_num, mercator = FALSE)
    
 return(points)
}

which gives me the error: Error in gglocator(n = point_num, mercator = FALSE) : ggplot graphic not detected in current device

It works fine if I do it line by line outside the function.
What am I missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Running ggplot inside a function doesn’t automatically print the produced ggplot object the way it does in the console.

Remember that in an interactive session in the console, any object returned by the code you type will be automatically printed: if you type sum(1:5) in the console, then the result [1] 15 is printed to the console. However, if you randomly include the line sum(1:5) in the middle of a function, it will have no effect and the result is not printed. The same is true of ggplot objects.

So the solution is to wrap your plotting code in an explicit call to print:

library(ggmap)

my_function<- function(point_num) {

 x11()

 print(iris %>% 
   ggplot()+
     aes(Sepal.Width,Sepal.Length)+
     geom_point())

 points <- gglocator(n = point_num, mercator = FALSE)

 return(points)
}

my_function(1)

#>   Sepal.Width Sepal.Length
#> 1    2.707581     5.196849
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading