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
The function geom_point() adds a layer of points to your plot, which creates a scatterplot.
Categorical variables in mpg include: manufacturer, model, trans (type of transmission), drv (front-wheel drive, rear-wheel, 4wd), fl (fuel type), and class (type of car). Continuous varibles in R are called doubles or integers.
aes() is a quoting function. This means that its inputs are quoted to be evaluated in the context of the data. This makes it easy to work with variables from the data frame because you can name those directly. The flip side is that you have to use quasiquotation to program with aes() .
The default position for geom_boxplot() is "dodge2" , which is a shortcut for position_dodge2. This position adjustment does not change the vertical position of a geom but moves the geom horizontally to avoid overlapping other geoms. See the documentation for position_dodge2() for additional discussion on how it works.
Your problem is that aes
doesn't know your function's environment and it only looks within global environment
. So, the variable dat
declared within the function is not visible to ggplot2
's aes
function unless you pass it explicitly as:
showplot1<-function(indata, inx, iny) { dat <- indata p <- ggplot(dat, aes(x=dat[,inx], y=dat[,iny]), environment = environment()) p <- p + geom_point(size=4, alpha = 0.5) print(p) }
Note the argument environment = environment()
inside the ggplot()
command. It should work now.
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