tastycanofmalk
tastycanofmalk

Reputation: 628

Use variable name as plot title with lapply

I need to display between 1-3 graphs, and I want the titles of the graphs to be based on the variable name that used.

I can get this to work how I want below:

library(grid)
library(ggplot2)
library(gridExtra)

a1 <- sample(1:100)
a2 <- sample(1:100)
a3 <- sample(1:100)

make_graph <- function(x, y=deparse(substitute(x))){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

g1 <- make_graph(a1)
g2 <- make_graph(a2)
g3 <- make_graph(a3)
grid.arrange(g1,g2,g3)

But this becomes inefficient when I need to include conditional statements if there are only 1 or 2 samples (i.e. only a1, or a1 & a2).

I got everything to work below, with the exception of the correct titles:

library(grid)
library(ggplot2)
library(gridExtra)

a1 <- sample(1:100)
a2 <- sample(1:100)
a3 <- sample(1:100)

sample_list <- paste0("a", seq_len(3))

make_graph <- function(x, y=deparse(substitute(x))){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

graphs_list <- lapply(mget(sample_list), make_graph)
do.call("grid.arrange", graphs_list)

With the above code I get the correct functionality, but deparse() in make_graph() seems to have some issues, I assume due to being called with lapply. So instead of the titles I had in the initial example ("a1", "a2", "a3"), I instead get "X[[1L]]", "X[[2L]]", "X[[3L]]".

I've also tried altering the lapply function, but this only gives me the first "title" in the list:

sample_list <- paste0("a", seq_len(3))

make_graph <- function(x, y){
        time <- 1:100
        dfp <- data.frame(time, x)
        ggplot(dfp, aes(x=time, y=x)) + geom_point() +
        ggtitle(y)
}

graphs_list <- lapply(mget(sample_list), make_graph, y=sample_list)
do.call("grid.arrange", graphs_list)

I'm not sure of the best approach to accomplish what I'm trying to do here. Thanks for any help.

Upvotes: 3

Views: 1572

Answers (1)

MrFlick
MrFlick

Reputation: 206197

You are right about those variable names coming from lapply. So that deparse strategy isn't a good one in that case. But since you made it super easy to pass along the title, you can just use Map rather than lapply.

graphs_list <- Map(make_graph, mget(sample_list), sample_list)
do.call("grid.arrange", graphs_list)

This gives the desired result.

sample plot

Upvotes: 3

Related Questions