I have following simple function but its ggplot command does not work. The command works all right when given from 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 to use aes_string
instead of aes
; and also using x=first, y=second
. Things improve and one point is plotted! X and Y axes show numbers related to that point as the label. Only the first row is being plotted. Where is the problem. Thanks for your help.
(As per my initial suggestion and your confirmation)
It was about how you were trying to pass string arguments of variable names into your fn.
ggplot(gdf, aes(first, second))
would work fineaes_string(first,second)
inside your function testfn, since you're now passing variable names indirectly, through the string-variables first,second.first,second
are strings, yes you do need to quote them when you call the fn. (I'm not sure what language mechanism ggplot's aes()
uses to not need strings, but whatever. Use quotes.)quote()
command in RSo the aes_string
version works fine for me.
# 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With