5

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.

Tung
  • 26,371
  • 7
  • 91
  • 115
  • `lapply` can't access the names of the list you pass it. See here: https://stackoverflow.com/a/9950217/4738478 – zlipp Apr 20 '18 at 14:19

1 Answers1

2

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

Tung
  • 26,371
  • 7
  • 91
  • 115
  • Hey, first of all thanks for your help ! I think I understand the use of rlang::sym and !! in aes. Unfortunately I cannot reproduce the graph in the image below with by copy-pasting the code you provided. I get the following error: "Error in !x.variable : invalid argument type" –  Apr 23 '18 at 07:20
  • You need the development version of `ggplot2`. See that line of code in my answer. Make sure to restart `R` before installing – Tung Apr 23 '18 at 07:43
  • 1
    You're right. I didn't install the development version of ggplot2. Works like a charm right now.. thanks ! –  Apr 23 '18 at 12:55