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?
CodePudding user response:
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