Column Names As Parameters with GGplot2

Another example of using column names as parameters with quo, this time within ggplot2. A snippet of the data:

  day   id stress performance
1   1 Josh      8           8
2   2 Josh      9          12
3   3 Josh      4          17
4   4 Josh      8           6
5   5 Josh      8          15
6   6 Josh      8          16

Let’s say we want to plot each person’s stress over time: three time-series trajectories.

library(tidyverse)
library(ggplot2)

ggplot(df, aes(x = day, y = stress, color = id)) + 
  geom_point() + 
  geom_line()

Great, but imagine having a data set with 300 different DVs. Instead of re-calling ggplot each time we can create a function where the column (DV) is the paramter.

plot_it <- function(col_name){
  
  g <- ggplot(df, aes(x = day, y = !!col_name, color = id)) + 
  geom_point() + 
  geom_line()
  
  return(g)
  
}

Note the !! before the parameter. Now, to plot the new graph we use quo within the function call.

plot_it(quo(performance))

Bo\(^2\)m =)