Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename columns with a named lookup vector in ggplot2?

Tags:

r

dplyr

ggplot2

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".

like image 994
Matthew Henderson Avatar asked Jan 26 '26 04:01

Matthew Henderson


1 Answers

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

like image 130
TimTeaFan Avatar answered Jan 28 '26 17:01

TimTeaFan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!