Ggplot - Select by column ID

ggplot2

#1

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?

Thanks


#2

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.


#3

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

library(tidyverse)

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

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


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


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


#4

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)) +
      geom_col()

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


#5

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

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