3

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.

3

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.