tags:

views:

45

answers:

1
ggplot() +
layer(
 data = diamonds, mapping = aes(x = carat, y = price),
 geom = "point", stat = "identity"
)

In the above example, I am wondering if I can specify the parameters for the "aes" function by indexes.

I know that carat and price correspond to the 1st and 8th elements in the names array of diamond. Can you advice why the following does not work?

ggplot() +
layer(
 data = diamonds, mapping = aes(x = names(diamonds)[1], y = names(diamonds)[8]),
 geom = "point", stat = "identity"
)

Thanks, Derek

+1  A: 

The second version does not work because names(diamonds)[1] is "carat" and not carat. Use aes_string instead of aes for this to work.

ggplot( data = diamonds, mapping = aes_string(x = names(diamonds)[1], y = names(diamonds)[8]), stat = "identity")+ geom_point()

EDIT: To deal with names that have illegal characters, you have to do enclose them in backticks (that's the case any time you want to use them):

dd <- data.frame(1:10, rnorm(1:10))
names(dd) <- c("(PDH-TSV 4.0)(ET)(240)", "Y")
nms <- paste("`", names(dd), "`", sep="")
ggplot(dd, mapping=aes_string(x=nms[1], y=nms[2])) + geom_point()
Aniko
while aes_string works for one-word-names in data frame, it seems to have dealing with names that has space and punctuation.For example, it shows the follow error when the name is "(PDH-TSV 4.0) (Eastern Daylight Time)(240)"Error in parse(text = x) : unexpected numeric constant in "(PDH-TSV 4.0"
Derek
@Derek: I edited the answer to address your problem.
Aniko