Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Addressing x and y in aes by variable number

Tags:

r

ggplot2

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 
like image 889
Vasily A Avatar asked Mar 10 '13 14:03

Vasily A


People also ask

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

Which variables in mpg are categorical?

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.

What is AES () in ggplot?

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() .

What's the default position adjustment for Geom_boxplot ()?

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.


1 Answers

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.

like image 176
Arun Avatar answered Oct 17 '22 01:10

Arun