I need to draw a scatterplot with addressing variables by their column numbers instead of names, i.e. instead of ggplot(dat, aes(x=Var1, y=Var2))
I need something like ggplot(dat, aes(x=dat[,1], y=dat[,2]))
. (I say 'something' because the latter doesn't work).
Here is my code:
showplot1<-function(indata, inx, iny){
dat<-indata
print(nrow(dat)); # this is just to show that object 'dat' is defined
p <- ggplot(dat, aes(x=dat[,inx], y=dat[,iny]))
p + geom_point(size=4, alpha = 0.5)
}
testdata<-data.frame(v1=rnorm(100), v2=rnorm(100), v3=rnorm(100), v4=rnorm(100), v5=rnorm(100))
showplot1(indata=testdata, inx=2, iny=3)
# Error in eval(expr, envir, enclos) : object 'dat' not found
provisional solution I found for the moment:
But I don't really like it because in my real code, I need other columns from
indata
and here I will have to define all of them explicitly indat<-
...For completeness, I think it's safer to use column names instead of indices because column positions within a data frame can be changed causing unexpected results.
The
plot_duo
function below (taken from this answer) can use input either as strings or bare column namesApply
plot_duo
function across columns usingpurrr::map()
Created on 2019-02-18 by the reprex package (v0.2.1.9000)
Your problem is that
aes
doesn't know your function's environment and it only looks withinglobal environment
. So, the variabledat
declared within the function is not visible toggplot2
'saes
function unless you pass it explicitly as:Note the argument
environment = environment()
inside theggplot()
command. It should work now.I strongly suggest using
aes_q
instead of passing vectors toaes
(@Arun's answer). It may look a bit more complicated, but it is more flexible, when e.g. updating the data.And here's the reason why it is preferable:
Note: As of ggplot2 v2.0.0
aes_q()
has been replaced withaes_()
to be consistent with SE versions of NSE functions in other packages.Try:
Edited to show what's happening - aes_string uses quoted arguments, names gets them using your numbers.
A variation on @Shadow's answer using new features from
ggplot2 V3.0.0
:ensym
creates a symbol from the string contained in a variable (so we first have to create those variables at the start of the function), then!!
unquotes it, which means it will work as if you had fed the function raw names.!!
works only in the context of functions designed to support it, usually tidyverse functions, else it just means "not not" (similar toas.logical
)..