Ggplot does not work in a function, passing variable names as strings

I have a simple function, but its ggplot command does not work. The command works correctly if given from the command line:

> testfn <- function(gdf, first, second){          
   library(ggplot2) 
   print(ggplot(gdf, aes(first, second)) + geom_point()) 
}                                                                                              
>
> testfn(mydataf, vnum1, vnum2)   
    Error in eval(expr, envir, enclos) : object 'second' not found
> 
> ggplot(mydataf, aes(vnum1, vnum2)) + geom_point()

>  (plots graph without any error)

I tried using aes_stringinstead aes; as well as using x=first, y=second. Things are improving and one point is built! The X and Y axes show the numbers associated with this point as a label. Builds only the first row. What is the problem. Thank you for your help.

+4
source share
2 answers

(According to my initial suggestion and your confirmation)

It was about how you tried to pass the string arguments of variable names to your fn.

  • ggplot(gdf, aes(first, second))
  • , . , , aes_string(first,second) testfn, , .
  • , - first,second , , , fn. ( , ggplot aes() , , . .)
  • . quote() R
+4

, aes_string .

# set-up and sample data
library(ggplot2) 
set.seed(1)
mydataf <- data.frame(vnum1=rnorm(10), 
                      vnum2=rnorm(10))
# aes_string version called with characters
testfn <- function(gdf, first, second){            
  print(ggplot(gdf, aes_string(x=first, y=second)) + geom_point()) 
}                                                                                              
# aes_string version called with variables
testfn2 <- function(gdf, first, second){  
  print(ggplot(gdf, aes_string(x=deparse(substitute(first)), 
                               y=deparse(substitute(second)))) + 
          geom_point())
}     
# 3 times the same plot
ggplot(mydataf, aes(vnum1, vnum2)) + geom_point()
testfn(mydataf, "vnum1", "vnum2")   
testfn2(mydataf, vnum1, vnum2)   
+2

Source: https://habr.com/ru/post/1538692/


All Articles