3

If you rename your dataframe columns with a lookup for purposes of analysis.

lookup <- c(x = "X Column", y = "Y Column")
df <- df_raw %>% rename(all_of(lookup))
... pipeline code ...

How can I reverse the mapping to label the columns for my ggplot?

df %>%
  ggplot(aes(x,y)) %>%
  geom_line() %>%
  ## some_function(lookup) - maps x -> "X Column", y -> "Y Column"

My desired output is a plot with the x-axis labelled "X Column" and a y-axis labelled "Y Column".

1 Answers1

4

You can construct a reverse lookup vector and then pipe into ggplot:

lookup <- c(x = "X Column", y = "Y Column")
lookup_rev <- setNames(names(lookup), lookup)

df %>%
  rename(all_of(lookup_rev)) %>%
  ggplot(aes(`X Column`,`Y Column`)) %>%
  geom_line() %>%
  ## plot continues

Alternatively we can splice our lookup vector into labs() with the triple bang operator !!!. This only works, if the column names are x and y.

library(tidyverse)

lookup <- c("x" = "Sepal.Length", "y" = "Sepal.Width")

iris %>%
  rename(all_of(lookup)) %>%
  ggplot(aes(x,y)) +
  geom_point() +
  labs(!!! lookup)

enter image description here

TimTeaFan
  • 17,549
  • 4
  • 18
  • 39