Search code examples
rggplot2lapplytidyevalnse

How to set ggplot x-label equal to variable name during lapply?


I'm making plots of one y variable against multiple x variables. I have a working solution using lapply. However, I can't manage to write the name of the x variable as the x label for each plot. Here's a simplified example of what I have:

The goal is to plot the y variable against each x variable resulting in three plots and adding the name of each x variable as the x axis label.

Generate a dataframe with one y variable and three x variables:

df <- data.frame(y.variable=c(11:20), x1=c(21:30),x2=c(1:10),x3=c(31:40))

A function that is supposed to retrieve the variable name as a string:

get_name <- function(v1) {deparse(substitute(v1))}

The function that generates the plot of y against an x variable:

generate_plot <- function(x.variable) {ggplot(data = df, aes(x.variable, y.variable )) +geom_point()  + xlab(get_name(variable.name))}

A call to lapply to perform generate_plot on each column of df:

lapply(df, generate_plot)

This results in three plots, each of which has "variable.x" as its x-label instead of the desired variable name x1, x2 and x3.


Solution

  • I modify your generate_plot a little bit and use the version of ggplot2 (> v3.0.0) which supports tidy evaluation

    Explanation:

    • Inside the function, we use rlang::sym to turn a string into a symbol then unquote it inside aes using !! (bang bang)

    • To call the function, use purrr::map to loop through df column names

    See more:

    library(tidyverse)
    
    df <- data.frame(y.variable=c(11:20), 
                     x1=c(21:30), x2=c(1:10), x3=c(31:40))
    
    generate_plot2 <- function(df, x.variable) {
      x.variable <- rlang::sym(x.variable)
    
      ggplot(data = df, aes(!! x.variable, y.variable )) +
        geom_point() + 
        xlab(x.variable)
    }
    
    names(df)[-1] %>% 
      map(~ generate_plot2(df, .x))
    

    enter image description here

    Created on 2018-04-20 by the reprex package (v0.2.0).