R ggplot: specify aes by index

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

In the above example, I wonder if I can specify the parameters for the "aes" function by index.

I know that the carat and price correspond to the 1st and 8th elements in the array of diamond names. Can you explain 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

+3
source share
1 answer

The second version does not work, because names(diamonds)[1]- "carat"and not carat. Use aes_stringinstead aesfor this.

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 must enclose them in backlinks (this is the case when 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()
+5
source

Source: https://habr.com/ru/post/1763150/


All Articles