1

I have two data frames with two columns each, however, each dataframe has unique variable names. I would like to specify the data in a call to ggplot and then, when mapping aesthetics to x and y for a column plot, to call the data anonymously and use indexing to specify which column goes to which aesthetic rather than using the variable names.

Tried using the .data pronoun, but it does not work with indexing. The below code works fine when specifying the variable name inside [[]].

library(tidyverse)

df1 <- data.frame(col1 = 1:10, col2 = 11:20)
df2 <- data.frame(var1 = 21:30,var2 = 31:40)

p <- geom_col(mapping = aes(x = .data[[,1]], y = .data[[,2]]))
ggplot(data = df1)+p
ggplot(data = df2)+p
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Duplicate of https://stackoverflow.com/q/15323269/5996475 – Liang Zhang Jul 09 '23 at 01:32
  • Does this answer your question? [Addressing x and y in aes by variable number](https://stackoverflow.com/questions/15323269/addressing-x-and-y-in-aes-by-variable-number) – Liang Zhang Jul 09 '23 at 01:34

1 Answers1

1

The .data pronoun doesn't support indexes. There's no way to make the same layer work with different column names. You'd have to create a helper function to build the mapping separately and extract the names of the columns as strings and use those to build the aes. One example would be

aes_index <- function(df, x=1, y=2) aes(x=.data[[names(df)[x]]], y=.data[[names(df)[y]]])
p <- geom_col()
ggplot(data = df1) + aes_index(df1) + p
ggplot(data = df2) + aes_index(df2) + p
MrFlick
  • 195,160
  • 17
  • 277
  • 295