R: Using a variable name in ggplot2

I am trying to run this code in ggplot2. It runs perfectly fine.

p <- ggplot(diamonds, aes(x= depth , y = price), color = cut))
p + geom_point()

Now I want to pass the x and y using variables so that I can use them in a for loop.

var1  <- colnames(diamonds)

var1 is a vector with the following variables:

[1] "carat"   "cut"     "color"   "clarity" "depth"   "table"  
 [7] "price"   "x"       "y"       "z"    

I use the following formula which should be equivalent to the above ggplot2.

p <- ggplot(diamonds, aes(x= var1[5] , y = var1[7]), color = cut))
p + geom_point()

This time around var1[5] is treated as a variable and var1[7] as another variable instead of them getting resolved into depth and price.

Is there a way around. I have used paste function but does not look to be working.

Upvotes: 3

Views: 964

Answers (1)

Bert Neef
Bert Neef

Reputation: 743

Like bunk allready mentioned in the comment: aes_string is the way to go:

library(ggplot2)
var1  <- colnames(diamonds)
p <- ggplot(diamonds, aes_string(x= var1[5] , y = var1[7]), color = cut)
p + geom_point()

Upvotes: 2

Related Questions