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.

989
  • 12,579
  • 5
  • 31
  • 53
  • 6
    use `aes_string` – Rorschach Nov 03 '15 at 05:36
  • Also see "Programming with ggplot2" to see how to write reusable functions with ggplot2: https://rpubs.com/hadley/97970 – mkhezr Oct 10 '18 at 18:02
  • Does this answer your question? [How to use a variable to specify column name in ggplot](https://stackoverflow.com/questions/22309285/how-to-use-a-variable-to-specify-column-name-in-ggplot) – user438383 Jul 10 '23 at 16:52

1 Answers1

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()
Bert Neef
  • 743
  • 1
  • 7
  • 14