Ggplot - Select by column ID

Hi all,

I am creating a ggplot, and wrapping it in a function (I am using, and am very excited about, the dev version of ggplot2 which uses tidyeval).

If I want to select a column based on its position (e.g. the first column) for the aes, is there an easy way to do it programmatically? I am used to the dplyr world, where I can just do

tbl1 %>% select(1)

I get the first column of tbl1. Can I do that in ggplot2-land?


Did you try doing it? What was the result?
If I understand correctly, all of the tidyverse packages are using the same mechanism to select names, specifically, tidyselect package. That means that ggplot2 is very likely using it as well and your approach should work.

This is what happens (although I may be making a dumb mistake)


tbl1 <- tibble(x1 = c("a", "b", "c"), x2 = 4:6, x3 = 7:9)

tbl1 %>% 
  ggplot(aes(x1, x2)) +

tbl1 %>%
  ggplot(aes(1, 2)) +

So simply putting in "1" or "2" doesn't work... (neither does vars(1))

OK, so I determined a hacky way around it, using tidyeval

    col1 <- sym(names(tbl1)[1])
    col2 <- sym(names(tbl1)[2])

    tbl1 %>%
      ggplot(aes(!!col1, !!col2)) +

If there is a better way, utilizing tidyselect, I will be happy to switch to that.

If you want to select by column ID, you can do the following:

tbl1 %>% 
  ggplot(aes(.[[1]], .[[2]])) +